Problem
For the given binary tree return the list which has sum of every paths in a tree. i.e Every path from root to leaf.
I've written following solution.
void check()
{
List<Integer> out = new ArrayList<>();
leafsum(root, 0, out);
System.out.println(out);
}
void leafsum(TreeNode root, int curr , List<Integer> sum)
{
if(root != null)
{
leafsum(root.left, curr+root.data, sum);
if(root.left == null && root.right == null ) sum.add(curr+root.data);
leafsum(root.right, curr+root.data, sum);
}
}
Inorder traversal of Tree
2 4 3 5 1 9 2 5 15
root = new TreeNode(5);
root.left = new TreeNode(4);
root.left.left = new TreeNode(2);
root.left.right = new TreeNode(3);
root.right = new TreeNode(9);
root.right.right = new TreeNode(5);
root.right.left = new TreeNode(1);
root.right.right.left = new TreeNode(2);
root.right.right.right = new TreeNode(15);
Output
[11, 12, 15, 21, 34]
I would like review about improvements and suggestions.