Total Accepted: 10147 Total Submissions: 37132
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] ]
/**
* 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>> list = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> path = new ArrayList<Integer>();
traverse(list, path, root, 0, sum);
return list;
}
public void traverse(ArrayList<ArrayList<Integer>> list, ArrayList<Integer> path, TreeNode root, int sum, int target) {
if (root == null) return;
path.add(root.val);
sum += root.val;
if (sum == target && root.left == null && root.right == null) list.add(new ArrayList<Integer>(path));
traverse(list, path, root.left, sum, target);
traverse(list, path, root.right, sum, target);
path.remove(path.size() - 1);
}
}