Path Sum II

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,是地址,是地址,是地址!!!!需要回溯,否则会有冗余。

posted on 2015-03-13 10:07  zhouzhou0615  阅读(116)  评论(0编辑  收藏  举报

导航