• [LeetCode] 437. Path Sum III


    You are given a binary tree in which each node contains an integer value.

    Find the number of paths that sum to a given value.

    The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

    The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

    Example:

    root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
    
          10
         /  
        5   -3
       /     
      3   2   11
     /    
    3  -2   1
    
    Return 3. The paths that sum to 8 are:
    
    1.  5 -> 3
    2.  5 -> 2 -> 1
    3. -3 -> 11

    路径和III。题意和前两个版本类似,但是这个题找的路径和,起点可以不是根节点,问满足路径和为sum的路径有多少。

    这个题出的非常好。思路是前缀和。利用前缀和的思路,递归统计你遍历到的子树上的前缀和presum是多少,并将这个前缀和存入hashmap。其他的部分就是很常规的前序遍历。

    时间O(n)

    空间O(n)

    Java实现

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode() {}
     8  *     TreeNode(int val) { this.val = val; }
     9  *     TreeNode(int val, TreeNode left, TreeNode right) {
    10  *         this.val = val;
    11  *         this.left = left;
    12  *         this.right = right;
    13  *     }
    14  * }
    15  */
    16 class Solution {
    17     public int pathSum(TreeNode root, int sum) {
    18         HashMap<Integer, Integer> map = new HashMap();
    19         map.put(0, 1);
    20         helper(root, 0, sum, map);
    21         return count;
    22     }
    23     
    24     int count = 0;
    25     public void helper(TreeNode root, int curSum, int target, HashMap<Integer, Integer> map) {
    26         // corner case
    27         if (root == null) {
    28             return;
    29         }
    30         
    31         // normal case
    32         curSum += root.val;
    33         if (map.containsKey(curSum - target)) {
    34             count += map.get(curSum - target);
    35         }
    36         if (!map.containsKey(curSum)) {
    37             map.put(curSum, 1);
    38         } else {
    39             map.put(curSum, map.get(curSum) + 1);
    40         }
    41         helper(root.left, curSum, target, map);
    42         helper(root.right, curSum, target, map);
    43         map.put(curSum, map.get(curSum) - 1);
    44     }
    45 }

    前缀和prefix sum题目总结

    LeetCode 题目总结

  • 相关阅读:
    ExtAspNet新版本发布v2.0beta4
    自己实现Rich Text Editor
    ExtAspNet应用技巧(五) 动态创建工具栏菜单
    IronPython的Hello World
    关于“跨语言调用”和“CLS(公共语言规范)”的一点体会
    文档,又是文档
    对项目目标的一点想法
    推荐一个WMI的查询分析器
    几个很不错的.NET 相关的FAQ和例子代码的连接
    用IronPython写winform程序
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13401680.html
Copyright © 2020-2023  润新知