这里注意是从根到叶子节点的和,我们递归就完事:
1.当前节点是NULL,返回false
2.当前节点是叶子节点,且和满足要求,返回true
3.递归左子树,递归右子树
这里判断和是否满足要求设计的很巧妙,通过参数传递减去当前节点的值。
代码如下所示:
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @param sum int整型
* @return bool布尔型
*/
bool hasPathSum(TreeNode* root, int sum) {
// write code here
if(root==NULL) return false;
if(!root->left&&!root->right&&sum-root->val==0){
return true;
}
return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum-root->val);
}
};