437. Path Sum III

Easy

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

这道题是要找到满足sum == target的路径个数,路径不一定是root to leaf, 但是必须是从上到下的。注意看一开始的错误解法。

submit 1 : int基本类型参数传入的是值,一旦传入是不会像传入引用类型的地址值一样, 在函数运行过程中地址所指向的值会改变的。所以你的res = 0传到函数里,res的值永远不会改变,一直是0.


image.png

submit 2 : 边界条件错误, for循环执行的条件是边界条件为true,跟while一样。所以这里你表达的意思应该是i >= 0,而不是i== 0, 后者作为边界条件时for循环根本不会执行。

53D7D469-5DB1-46DA-9151-9D35E1BC5AF2.png
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int pathSum(TreeNode root, int sum) {
        List<Integer> path = new ArrayList<>();
        return helper(root, path, sum); 
    }
    
    private int helper(TreeNode root, List<Integer> path, int sum){
        int res = 0;
        if (root == null){
            return res;
        }
        path.add(root.val);
        int pathSum = 0;
        for (int i = path.size() - 1; i >= 0; i--){
            pathSum += path.get(i);
            if (pathSum == sum){
                res++;
            }
        }
        res += helper(root.left, path, sum);
        res += helper(root.right, path, sum);
        path.remove(path.size() - 1);
        return res;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 题目 You are given a binary tree in which each node contain...
    miltonsun阅读 361评论 0 0
  • Keywords: double recursion, DFS You are given a binary tr...
    成江阅读 466评论 0 0
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,794评论 0 33
  • 想不多写函数,失败了,(╯‵□′)╯︵┻━┻ Java,首先要有一个函数记录某个点开始能找到符合累加和为sum的个...
    hyhchaos阅读 227评论 0 0
  • 好想为你写诗,可是不知写什么; 整日整日的想,可依旧没有好的句子; 说不出那些感人的话,也不知道怎么表达情感; 不...
    鬼谷摆摊阅读 281评论 1 1