1.题目描述
给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
说明: 叶子节点是指没有子节点的节点
2.解题思路
(1)因为求得时根节点到叶子节点的路径和,所以每一次遍历的中止条件是当前节点的左右节点都为空。
(2)使用一个中间变量temp对遍历过程中的节点值进行累加,当遍历到叶子节点时,如果temp与给定的sum相等,返回true,否则返回false。
(3)若当前节点有一子节点不为空时,对该子节点继续进行与上述相同的遍历。
/**
* 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 CountValue(TreeNode* root, int temp,int sum)
{
if(root!=NULL)
{
if(root->left==NULL&&root->right==NULL)
{
if((temp+root->val)==sum)
return true;
else
return false;
}
if(root->left!=NULL)
{
if(CountValue(root->left, temp+root->val, sum))
return true;
}
if(root->right!=NULL)
{
if(CountValue(root->right, temp+root->val, sum))
return true;
}
}
return false;
}
bool hasPathSum(TreeNode* root, int sum) {
if(root==NULL)
return false;
if(CountValue(root,0,sum))
return true;
else
return false;
}
};