首页 > 其他 > 详细

Path Sum II

时间:2015-03-13 10:40:49      阅读:297      评论:0      收藏:0      [点我收藏+]

Path Sum II

问题:

Given a binary tree and a sum, find all root-to-leaf paths where each path‘s sum equals the given sum.

思路:

  dfs + 回溯

我的代码:

技术分享
public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        if(root == null) return rst;
        List<Integer> list = new ArrayList<Integer>();
        helper(root, sum, list);
        return rst;
    }
    private List<List<Integer>> rst = new ArrayList<List<Integer>>();
    public void helper(TreeNode root, int sum, List<Integer> list)
    {
        if(root == null)    return;
        if(root.left == null && root.right == null)
        {
            if(sum == root.val)
            {
                list.add(root.val);
                rst.add(new ArrayList(list));
                list.remove(list.size() - 1);
            }
            return;
        }
        list.add(root.val);
        helper(root.left, sum - root.val, list);
        helper(root.right, sum - root.val, list);
        list.remove(list.size() - 1);
    }
}
View Code

学习之处:

  • 对于含有List的Dfs一定要记在心里面List需要remove,是地址,是地址,是地址!!!!需要回溯,否则会有冗余。

Path Sum II

原文:http://www.cnblogs.com/sunshisonghit/p/4334397.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!