112. The sum of the path
Given a binary tree and a destination and determines whether the root node to the leaf node in the tree path exists, all the nodes on this route, and equal to the target value is added.
Description: leaf node is a node has no child nodes.
Example:
Given the following binary tree, and the target and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
Returns true, because the presence of the target path and the root node to the leaf node 22 5-> 4-> 11-> 2.
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null) {
return sum - root.val == 0;
}
return hasPathSum(root.left, sum - root.val)
|| hasPathSum(root.right, sum - root.val);
}
}