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.
For example:
Given the below binary tree and sum = 22
,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
要求求出是否有一条路径和与给出的值相等,注意中间节点与叶子节点的判断:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(root == NULL) return false;
return checkSum(root, sum);
} bool checkSum(TreeNode* root, int sum)
{
if(root != NULL && sum == root->val && root->left == NULL && root->right == NULL){
return true;//上面这个判断确实是叶子节点,值也同时满足
}
else if(root == NULL)
return false;
else
return checkSum(root->left, sum - root->val) || checkSum(root->right, sum - root->val);
}
};
java版本的如下,递归版本的没上面那么麻烦:
public 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;
}
return hasPathSum(root.left, sum - root.val) ||
hasPathSum(root.right, sum - root.val);
}
}