您的位置:首页 > 其它

【Leetcode】Path Sum II (Sum)

2014-10-31 09:55 211 查看
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and 
sum
= 22
,
5
/ \
4   8
/   / \
11  13  4
/  \    / \
7    2  5   1


return

[
[5,4,11,2],
[5,8,4,5]
]


这道题和I不同点在于需要保存所有的路径,所以需要用一个二维arraylist来保存所有结果。先上代码,再逐段解析
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if (root == null)
return result;

ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(root.val);
helper(result, temp, sum - root.val, root);
return result;
}

public void helper(ArrayList<ArrayList<Integer>> result,
ArrayList<Integer> temp, int sum, TreeNode root) {
if (root.left == null && root.right == null && sum == 0) {
result.add(new ArrayList<Integer>(temp));
return;
}
if (root.left != null) {
temp.add(root.left.val);
helper(result, temp, sum - root.left.val, root.left);
temp.remove(temp.size() - 1);
}
if (root.right != null) {
temp.add(root.right.val);
helper(result, temp, sum - root.right.val, root.right);
temp.remove(temp.size() - 1);
}
}


保护现场的思路:
当发现这个元素不合格的时候,就需要把这个元素给清除掉。而这个元素一般都处在temp的最顶端,所以只需要移除最顶端的元素即可。这就是为什么要写成

temp.remove(temp.size()-1);

注意“跳出条件”有几点要说明

if (root.left == null && root.right == null && sum == 0) {
result.add(new ArrayList<Integer>(temp));
return;
}
1. 一定是sum==0的时候跳出,这一点和I是不同的,I是在(root.val == sum)的时候跳出的,因为递归时候放的是左边,但是减掉的是根节点的值,而II放的是左边,减的也是左边。
2. 为什么要用

result.add(new ArrayList<Integer>(temp));
而不直接用

result.add(temp);因为temp是一个引用,所以改变temp的值会改变result里面的值,所以必须新建一个ArrayList,这样就可以抛弃原来的引用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: