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:
1
2
3
4
5
6
7
8
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.
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,
1
2
3
4
5
6
7
8
9
10
11
12
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
DFS Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public ArrayList<LinkedList<Integer>> pathSum(TreeNode root, int sum) {
ArrayList<LinkedList<Integer>> res = new ArrayList<LinkedList<Integer>>();
if(root==null) return res;
LinkedList<Integer> pathlist = new LinkedList<Integer>();
dfs(root, sum, pathlist, res);
return res;
}
privatevoiddfs(TreeNode r, int sum, LinkedList<Integer> pathlist, ArrayList<LinkedList<Integer>> res){
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example,
1
/ \ 2 3 The root-to-leaf path 1->2 represents the number 12. The root-to-leaf path 1->3 represents the number 13. Return the sum = 12 + 13 = 25.