算法题目: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,
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
大致意思:给定一颗二叉树,决定是否存在一条从根结点到叶子结点的路径,使路径上的每个结点值的总和等于给定的sum,存在返回true,否则返回false。注意:一定是从根结点到叶子结点!!!
思路:递归做法,每到一个结点,用sum减去该结点的值,然后判断该结点是否为叶子结点,若是,判断sum==0?并返回true或false,否则就继续递归下去,递归退出条件为:树为空,返回false
bool hasPathCore(TreeNode* root,int sum)
{
if(root==NULL)return false;
sum-=root->val;
if(root->left==NULL&&root->right==NULL)
{
if(sum==0)return true;
else return false;
}
if(hasPathCore(root->left,sum)||hasPathCore(root->right,sum))
return true;
else
return false;
}
bool hasPathSum(TreeNode* root, int sum) {
if(root==NULL)return false;
return hasPathCore(root,sum);
}