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

Path Sum II

时间:2015-03-13 10:41:06      阅读:121      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!