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.
Note: A leaf is a node with no children.
Example:
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.
思路:
DFS,可以用中序遍历,逐个减去访问的节点值,比较时可以用sum-root.val的方式逐个减掉元素,最后只剩下当前节点值=当前sum即可
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null) {
return false;
}
if(root.left == null && root.right == null && root.val == sum) {
return true;
}
return(hasPathSum(root.left, sum - root.val) ||
hasPathSum(root.right, sum - root.val));
}
和112类似,只是这次要输出所有满足条件的path
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Return:
[
[5,4,11,2],
[5,8,4,5]
]
思路:
仍然采用112的逐个用sum-访问节点值的方法,只是这次要访问所有path,不能用112的return left || right, 而是都要访问,然后需要用一个Stack保存访问节点的值,访问完它的左右子树后pop掉这个值
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
Stack<Integer> stack = new Stack<>();
dfs(root, sum, stack, result);
return result;
}
public void dfs(TreeNode root, int sum, Stack<Integer> stack,
List<List<Integer>> result) {
if(root == null) {
return;
}
stack.push(root.val);
if(root.left == null && root.right == null && root.val == sum) {
ArrayList<Integer> tmp = new ArrayList<Integer>(stack);
result.add(tmp);
stack.pop();
return;
}
dfs(root.left, sum - root.val, stack, result);
dfs(root.right, sum - root.val, stack, result);
stack.pop();
}