llllmz

导航

112. 路径总和c

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
bool judge(struct TreeNode* root,int now,int sum){
    now+=root->val;
    if(!root->left&&!root->right){
        if(now==sum)  return true;
        return false;
    }
    bool a=false,b=false;
    if(root->left) a=judge(root->left,now,sum);
    if(root->right) b=judge(root->right,now,sum);
    return a||b;
}

bool hasPathSum(struct TreeNode* root, int targetSum) {
    if(!root) return false;
    return judge(root,0,targetSum);
}

结果:

posted on 2024-03-05 22:18  神奇的萝卜丝  阅读(10)  评论(0)    收藏  举报