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 + tree traverse.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> subset = new ArrayList<Integer>();
if(root == null) return result;
helper(root, sum, result, subset);
return result;
}
public void helper(TreeNode root, int target, ArrayList<ArrayList<Integer>> result, ArrayList<Integer> subset){
if(root.left == null && root.right == null){
if(root.val == target){
subset.add(root.val);
result.add(new ArrayList<Integer>(subset)); // new !!!!!!
subset.remove(subset.size()-1);
}
return;
}
subset.add(root.val);
if(root.left != null){ helper(root.left, target-root.val, result, subset);}
if(root.right != null) { helper(root.right, target-root.val, result, subset);}
subset.remove(subset.size()-1);
}
}
No comments:
Post a Comment