Leetcode 112. 路径总和

时间:2022-11-26 07:47:48
/**
 * 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 visit(TreeNode* r, int want, int now)
    {
        if(r==NULL) 
            return false;
        if(r->left==NULL && r->right==NULL)
        {
            //leaf
            return (now+r->val==want);
        }
        else
        {
            return visit(r->left, want, now+r->val) || visit(r->right, want, now+r->val);
        }
    }
    
    bool hasPathSum(TreeNode* root, int sum) {
        if(root == NULL)
            return false;
        return visit(root, sum, 0);
    }
};