Given a binary tree, find all paths that sum of the nodes in the path equals to a given numbertarget.
A valid path is from root node to any of the leaf nodes.
Example
Given a binary tree, and target =5:
1
/ \
2 4
/ \
2 3
return
[
[1, 2, 2],
[1, 4]
]
这题可用全子集的递归模板(即完成后再从后面减掉),还有一个重点则是path是从root 到 leave, leave的判断条件是左右子树为Null
还有就是往最后结果集合中加元素时,一定要hard copy
public class Solution {
/**
* @param root the root of binary tree
* @param target an integer
* @return all valid paths
*/
private int sum = 0;
public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) {
// Write your code here
List<List<Integer>> ans = new ArrayList<>();
List<Integer> cur = new ArrayList<>();
if (root == null) {
return ans;
}
sum = root.val;
cur.add(root.val);
bTreePathSumHelper(ans, cur, root, target);
return ans;
}
public void bTreePathSumHelper(List<List<Integer>> ans,
List<Integer> cur,
TreeNode root,
int target) {
if (root.left == null && root.right == null) {
if (sum == target) {
ans.add(new ArrayList<Integer>(cur));
}
return;
}
if (root.left != null) {
sum = sum + root.left.val;
cur.add(root.left.val);
bTreePathSumHelper(ans, cur, root.left, target);
sum = sum - cur.get(cur.size() - 1);
cur.remove(cur.size() - 1);
}
if (root.right != null) {
sum = sum + root.right.val;
cur.add(root.right.val);
bTreePathSumHelper(ans, cur, root.right, target);
sum = sum - cur.get(cur.size() - 1);
cur.remove(cur.size() - 1);
}
}
}
second batch 判断时一定要加上判断当前节点是否是根节点(root.left == null && root.right == null)
int sum = 0;
public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) {
// Write your code here
List<List<Integer>> ans = new ArrayList<>();
if (root == null) {
return ans;
}
List<Integer> cur = new ArrayList<>();
btpHelper(ans, cur, root, target);
return ans;
}
public void btpHelper(List<List<Integer>> ans, List<Integer> cur, TreeNode root, int target) {
if (root == null) {
return;
}
cur.add(root.val);
sum += root.val;
btpHelper(ans, cur, root.left, target);
btpHelper(ans, cur, root.right, target);
if (root.left == null && root.right == null && sum == target) {
ans.add(new ArrayList<>(cur));
}
sum -= cur.get(cur.size() - 1);
cur.remove(cur.size() - 1);
}