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]
]
分析:
看到二叉树,想递归,
看到find all,想回溯,继而想到 DFS。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(root == null) return result;
List<Integer> curr = new ArrayList<Integer>();
curr.add(root.val);
dfs(root, sum-root.val, curr, result);
return result;
}
private void dfs(TreeNode node, int remain, List<Integer> curr, List<List<Integer>> result){
if(node == null) return;
if(node.left==null && node.right==null && remain == 0){
result.add(new ArrayList<Integer>(curr));
return;
}
if(node.left != null){
curr.add(node.left.val);
dfs(node.left, remain-node.left.val, curr, result);
curr.remove(curr.size()-1);
}
if(node.right != null){
curr.add(node.right.val);
dfs(node.right, remain-node.right.val, curr, result);
curr.remove(curr.size()-1);
}
}
}