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

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

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

class Solution {
public:
    int Sum;
    bool mark = false;

    void LevelOrderDFS(TreeNode* root, int num) {
        if (!root) return;

        // 到达叶子节点,检查路径和
        if (!root->left && !root->right) {
            if (num == Sum) mark = true;
            return;
        }

        // 向下继续累加子节点的值
        if (root->left)  LevelOrderDFS(root->left,  num + root->left->val);
        if (root->right) LevelOrderDFS(root->right, num + root->right->val);
    }

    bool hasPathSum(TreeNode* root, int sum) {
        if (!root) return false;
        Sum = sum;
        mark = false;               // 重置全局状态
        LevelOrderDFS(root, root->val);
        return mark;
    }
};

全部评论

相关推荐

NBA球星伦纳德:jd是这样的,工作连拧螺丝都算不上
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务