题解 | #二叉树中和为某一值的路径(一)#

二叉树中和为某一值的路径(一)

https://www.nowcoder.com/practice/508378c0823c423baa723ce448cbfd0c

自己写的dfs都没这么简洁,这个代码好就好在每层都减去了路径上的总和

/**
 * 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==nullptr) 
            return false;
        if(root->left == nullptr && root->right == nullptr) return root->val == sum;
        return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
    }
};

全部评论

相关推荐

移动信息技术中心 金种子 50+n w
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务