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

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

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;
    }
};
牛客刷题记录 文章被收录于专栏

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

全部评论

相关推荐

明天不下雨了:兄弟你是我今天看到的最好看的简历(我说的是简历风格跟简历书写)把985 211再搞亮一点。投boss就说;您好,我华科(985)研二在读,本科211。对您的岗位很感兴趣,希望能获得一次投递机会。
点赞 评论 收藏
分享
暮雨轻歌:看起来hr不能接受我菜查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务