Topic : Input a binary tree and an integer, and print out all paths where the sum of node values in the binary tree is the input integer. Starting from the root node of the tree and going down to the nodes passed by the leaf nodes form a path.
Example:
Given the following binary tree, and the goal and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return:
[
[5,4,11,2],
[5,8,4,5]
]
prompt:
节点总数 <= 10000
Answer :
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<List<Integer>> list1 = new ArrayList<List<Integer>>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
int total = 0;
dfs(root, sum, total, new ArrayList<Integer>());
return list1;
}
public void dfs(TreeNode root, int sum,int total, List<Integer> list){
if(root == null) return;
list.add(root.val);
total += root.val;
if(total == sum && root.left == null && root.right == null) {
list1.add(new ArrayList<>(list));
}else{
dfs(root.left, sum, total, list);
dfs(root.right, sum, total, list);
}
list.remove(list.size() - 1);
}
}