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]
]
Method:
DFS
Solution:
Time: O(n) Space: O(n)
/** * Definition for binary tree * class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { * val = x; * left=null; * right=null; * } * } */ public class Solution { public ArrayList<ArrayList<Integer>> pathSum(TreeNode A, int B) { ArrayList<ArrayList<Integer>> result = new ArrayList<>(); ArrayList<Integer> curr = new ArrayList<>(); helper(result, curr, A, B); return result; }
private void helper(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> curr, TreeNode A, int B) { if (A == null) return; if (A.left == null && A.right == null) { if (A.val == B) { curr.add(A.val); result.add(new ArrayList<>(curr)); curr.remove(curr.size() - 1); return; } } if (A.left != null) { curr.add(A.val); helper(result, curr, A.left, B - A.val); curr.remove(curr.size() - 1); } if (A.right != null) { curr.add(A.val); helper(result, curr, A.right, B - A.val); curr.remove(curr.size() - 1); } } }