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.
判断一个二叉树是否存在从根到叶子的路径,其间节点的和=给定的和
注意是从根到叶子,假如上图中给定和是20,那么从5->4->11的路径虽然满足,但是因为11不是叶子,所以依然不成立。
这个题还是用前序,中序,后序遍历来解,这里的思路用前序遍历
代码:
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
int result = 0;
if (preTraversal(root, sum, result)) {
return true;
}
return false;
}
public boolean preTraversal(TreeNode root, int sum, int result) {
if (root == null) {
return false;
}
result += root.val;
//must be leaves..
if (result == sum && root.left == null && root.right == null) {
return true;
}
if (preTraversal(root.left, sum, result)) {
return true;
}
if (preTraversal(root.right, sum, result)) {
return true;
}
result -= root.val;
return false;
}