标签:
Given a binary tree and a sum, find all root-to-leaf paths where each path‘s sum equals the given sum.
For example:sum
= 22,
5
/ 4 8
/ / 11 13 4
/ \ / 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]题意:求路径和为sum的所有可能。
思路:和上一题差不多,多个记录而已。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private List<List<Integer>> ans = new ArrayList<List<Integer>>();
private int data[] = new int[1000];
private void dfs(TreeNode root, int sum, int cur) {
if (root == null) return;
if (root.left == null && root.right == null && root.val == sum) {
List<Integer> tmp = new ArrayList<Integer>();
for (int i = 0; i < cur; i++) tmp.add(data[i]);
tmp.add(sum);
ans.add(tmp);
return;
}
sum -= root.val;
data[cur] = root.val;
if (root.left != null) dfs(root.left, sum, cur+1);
if (root.right != null) dfs(root.right, sum, cur+1);
}
public List<List<Integer>> pathSum(TreeNode root, int sum) {
ans.clear();
dfs(root, sum, 0);
return ans;
}
}
标签:
原文地址:http://blog.csdn.net/u011345136/article/details/45618307