码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Path Sum Lintcode

时间:2017-02-03 11:02:01      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:panel   footer   tar   log   lin   lis   sub   res   node   

Given a binary tree, find all paths that sum of the nodes in the path equals to a given number target.

A valid path is from root node to any of the leaf nodes.

Example

Given a binary tree, and target = 5:

     1
    /    2   4
  /  2   3

return

[
  [1, 2, 2],
  [1, 4]
]
这道题居然一遍bug free了。。。但好像空间复杂度有点高。。。
public class Solution {
    /**
     * @param root the root of binary tree
     * @param target an integer
     * @return all valid paths
     */
    public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) {
        List<List<Integer>> res = new ArrayList<>();
        
        helper(root, target, res, new ArrayList<Integer>());
        return res;
    }
    public TreeNode helper(TreeNode root, int target, List<List<Integer>> res, List<Integer> sub) {
        if (root == null) {
            return null;
        }
        sub.add(root.val);
        
        TreeNode left = helper(root.left, target - root.val, res, new ArrayList<>(sub));
        TreeNode right = helper(root.right, target - root.val, res, new ArrayList<>(sub));
        
        if (left == null && right == null && target - root.val == 0) {
            res.add(sub);
        }
        
        return root;
        
    }
}

看了下答案,原来还可以改进一下,每次回去的时候把添加的值去掉,这样就不用不停地建新的了。对递归的认识好像又深了一点呢。

 

Binary Tree Path Sum Lintcode

标签:panel   footer   tar   log   lin   lis   sub   res   node   

原文地址:http://www.cnblogs.com/aprilyang/p/6362083.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!