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

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

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

递归方法

/**
 * 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)
            return false;
        stack<TreeNode*> Stack;
        TreeNode* tmp = root;
        Stack.push(tmp);
        if(!tmp->left && !tmp->right && sum == tmp->val)
            return true;
        return hasPathSum(root->right, sum-tmp->val) || hasPathSum(root->left, sum-tmp->val);
    }
};

非递归方法

/**
 * 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 == NULL)
        {
            return false;
        }
        //首先对树进行前序遍历,会用到栈
        TreeNode* tmp = root;
        stack<TreeNode*> Stack;
        int cal_sum = 0;
        Stack.push(tmp);//根节点入栈
        while(Stack.size()>0)//cal_sum != sum )//栈不为空
        {
            TreeNode* node = Stack.top();
            Stack.pop();

            if(!node->left && !node->right)
            {
                cal_sum = node->val;
                if(cal_sum == sum)
                    return true;
            }
            if(node->right)
            {
                node->right->val = node->val + node->right->val;
                Stack.push(node->right);
            }
            if(node->left)
            {
                node->left->val = node->val + node->left->val;
                Stack.push(node->left);
            }
        }
        return false;
    }
};
牛客刷题记录 文章被收录于专栏

记录自己的刷题记录,刷过的题的解法

全部评论

相关推荐

当初高考报计算机真是造大孽了啊!卷的飞起!哪都是计算机的人,考研,考公,找工作全他奶的计算机的人,太难了。国企也是。关键一届比一届卷,造大孽了!
_Lyrics_:因为计算机,没有体验到快乐的大学研究生时光,好不容易修完课程就要出去实习,看着别人专业可以一起搓麻将,游山玩水,而我却要自己一个人住在北上不到十平米的出租屋,每天两点一线
点赞 评论 收藏
分享
双非阴暗爬行:我来看看笑死我了,这名字取得好想笑(没有不好的意思)
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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