Given a binary tree, find all paths that sum of the nodes in the path equals to a given number target
.
A valid path is from root node to any of the leaf nodes.
Example
Example 1:
Input:
{1,2,4,2,3}
5
Output: [[1, 2, 2],[1, 4]]
Explanation:
The tree is look like this:
1
/ \
2 4
/ \
2 3
For sum = 5 , it is obviously 1 + 2 + 2 = 1 + 4 = 5
Example 2:
Input:
{1,2,4,2,3}
3
Output: []
Explanation:
The tree is look like this:
1
/ \
2 4
/ \
2 3
Notice we need to find all paths from root node to leaf nodes.
1 + 2 + 2 = 5, 1 + 2 + 3 = 6, 1 + 4 = 5
There is no one satisfying it.
思路:注意递归的定义,传进去的是root,和root.val,那么curSum代表的意义就是加入了当前传进去node的value的curSum;
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/*
* @param root: the root of binary tree
* @param target: An integer
* @return: all valid paths
*/
public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) {
List<List<Integer>> lists = new ArrayList<List<Integer>>();
if(root == null) {
return lists;
}
List<Integer> list = new ArrayList<Integer>();
list.add(root.val);
dfs(root, root.val, target, lists, list);
return lists;
}
private void dfs(TreeNode node,
int curSum, // 表示加入了node.val的curSum;
int target,
List<List<Integer>> lists,
List<Integer> list) {
if(node.left == null && node.right == null) {
if(target == curSum) {
lists.add(new ArrayList<Integer>(list));
}
}
// search left;
if(node.left != null) {
curSum += node.left.val;
list.add(node.left.val);
dfs(node.left, curSum, target, lists, list);
list.remove(list.size() -1);
curSum -= node.left.val;
}
// search right;
if(node.right != null) {
curSum += node.right.val;
list.add(node.right.val);
dfs(node.right, curSum, target, lists, list);
list.remove(list.size() -1);
curSum -= node.right.val;
}
}
}