For example:
Given the below binary tree and
sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1return true, as there exists a root-to-leaf path
5->4->11->2
for which the sum is 22.
---
Solution: When the root node is null, return false (even when sum is 0). Recurse down the tree until you find a leaf node. For each recursion, subtract the value of the current node from sum. When we get to a leaf node, if the sum is 0, then return true.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) return false;
return recurse(root, sum);
}
private boolean recurse(TreeNode node, int sum) {
sum -= node.val;
if (node.left == null && node.right == null) return (sum == 0);
if (node.left != null && recurse(node.left, sum)) return true;
if (node.right != null && recurse(node.right, sum)) return true;
return false;
}
}
No comments:
Post a Comment