Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
public class Solution { public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) { // Note: The Solution object is instantiated only once and is reused by each test case. ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> list = new ArrayList<Integer>(); recursion(result,list,root,sum); return result; } public void recursion(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> list, TreeNode root, int sum){ if(root == null) return; if(sum == root.val &&root.left == null && root.right == null ){ //checking condition, forgot left and right list.add(root.val); result.add(list); } else{ ArrayList<Integer> left = new ArrayList<Integer>(); ArrayList<Integer> right = new ArrayList<Integer>(); left.addAll(list); left.add(root.val); right.addAll(list); right.add(root.val); recursion(result,left,root.left,sum-root.val); recursion(result,right,root.right,sum-root.val); } } }
Mistake:
Learned: difference between list.add and list.addall . Return list problem has to add up previous items