LetCode 112. 路径总和

/**
 * 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 hasPathSum(root, 0, sum);
    }
    
    bool hasPathSum(TreeNode* root, int sum, int target){
        if (root == NULL)
            return false;
        if (root->left == NULL && root->right == NULL)
            return sum + root->val == target;
        return hasPathSum(root->left, sum + root->val, target) || hasPathSum(root->right, sum + root->val, target);
    }
};

static int x=[](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();

猜你喜欢

转载自blog.csdn.net/wbb1997/article/details/81089398
今日推荐