您的位置:首页 > 其它

LeetCode Path Sum II

2015-07-07 12:10 288 查看
Description:

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]
]

Solution:

还是一样的DFS。

和Path Sum相比,有一个细节:DFS的每个层次递归的条件有所不同。

import java.util.*;

public class Solution {
int targetSum;
List<List<Integer>> list = new ArrayList<List<Integer>>();

public List<List<Integer>> pathSum(TreeNode root, int sum) {
if (root == null)
return list;
this.targetSum = sum;
ArrayList<Integer> array = new ArrayList<Integer>();
array.add(root.val);
dfs(root, root.val, array);
return list;
}

void dfs(TreeNode root, int tempSum, ArrayList<Integer> array) {
if (root.left == null && root.right == null) {
if (tempSum == targetSum)
list.add(new ArrayList<Integer>(array));
}
if (root.left != null) {
array.add(root.left.val);
dfs(root.left, tempSum + root.left.val, array);
array.remove(array.size() - 1);
}
if (root.right != null) {
array.add(root.right.val);
dfs(root.right, tempSum + root.right.val, array);
array.remove(array.size() - 1);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: