Day36: [LeetCode简单] 112. 路径总和

Day36: [LeetCode简单] 112. 路径总和

题源:

来自leetcode题库:

https://leetcode-cn.com/problems/path-sum/

代码:

dirty code凑合看吧

/**
 * 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:
    int Sum;
    bool f(TreeNode* root,int sum){
        if(root){
            if(root->left==NULL&&root->right==NULL){
                if(sum+root->val==Sum) return true;
                else return false;
            } //是叶子结点
            return f(root->left,sum+root->val)||f(root->right,sum+root->val);
        }else return false;
    }
    bool hasPathSum(TreeNode* root, int sum) {
        if(!root) return false;
        Sum=sum;
        return f(root,0);
    }
};
发布了49 篇原创文章 · 获赞 13 · 访问量 510

猜你喜欢

转载自blog.csdn.net/qq2215459786/article/details/103639035