二叉树中是否存在节点和为指定值的路径

二叉树中是否存在节点和为指定值的路径

http://www.nowcoder.com/questionTerminal/508378c0823c423baa723ce448cbfd0c

先序遍历,套模版就是了。

class Solution {
public:
    /**
     *
     * @param root TreeNode类
     * @param sum int整型
     * @return bool布尔型
     */
    bool hasPathSum(TreeNode* root, int sum) {
        // write code here
        if (!root) return false;
        return preOrder(root, sum, 0);
    }

    bool preOrder(TreeNode *root, int &sum, int current) {
        if (!root) return false;
        current += root->val;
        if (!root->left && !root->right && sum == current) return true;
        return preOrder(root->left, sum, current) || preOrder(root->right, sum, current);
    }
};
刷遍天下无敌手 文章被收录于专栏

秋招刷题历程

全部评论

相关推荐

评论
13
收藏
分享

创作者周榜

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