For 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./**
* Definition for binary tree
* 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 findPath(root, sum);
}
public boolean findPath(TreeNode node, int sum) {
if(node.left==null && node.right==null) {
if(node.val==sum) {
return true;
} else {
return false;
}
} else if(node.left!=null && node.right!=null) {
return findPath(node.left, sum - node.val) || findPath(node.right, sum - node.val);
} else if(node.left==null && node.right!=null) {
return findPath(node.right, sum - node.val);
} else {
return findPath(node.left, sum - node.val);
}
}
}
/**
* 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 node, int sum) {
if (node == null) {
return false;
}
sum -= node.val;
if (node.left == null && node.right == null && sum == 0) {
return true;
}
return hasPathSum(node.left, sum) || hasPathSum(node.right, sum);
}
}
没有评论:
发表评论