码迷,mamicode.com
首页 > 其他好文 > 详细

Path Sum - LeetCode

时间:2019-03-26 01:35:37      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:uila   problem   tco   存在   ble   .com   str   leetcode   treenode   

题目链接

Path Sum - LeetCode

注意点

  • 不要访问空结点
  • val会有负值

解法

解法一:递归,DFS。首先判空,若当前结点不存在,则直接返回false,如果如果输入的是一个叶节点,则比较当前叶节点的值和参数sum值是否相同,若相同,返回true,否则false。 这个条件也是递归的终止条件。接下来就开始递归,对非叶节点开始判断,左右子树都进行判断。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum) {
        if(!root) return false;
        if(root->val == sum && !root->left && !root->right) return true;
        return hasPathSum(root->left,sum-(root->val)) || hasPathSum(root->right,sum-(root->val));
    }
};

技术图片

解法二:非递归,先序遍历。先序遍历二叉树,左右子结点都需要加上其父结点值,这样当遍历到叶结点时,如果和sum相等了,那么就说明一定有一条从root过来的路径。。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum) {
        if(!root) return false;
        stack<TreeNode*> s;
        s.push(root);
        while(!s.empty())
        {
            TreeNode* n = s.top();s.pop();
            if(!n->left&&!n->right)
            {
                if(n->val == sum) return true;
            }
            if(n->left)
            {
                n->left->val += n->val;
                s.push(n->left);
            }
            if(n->right)
            {
                n->right->val += n->val;
                s.push(n->right);
            }
        }
        return false;
    }
};

技术图片

小结

Path Sum - LeetCode

标签:uila   problem   tco   存在   ble   .com   str   leetcode   treenode   

原文地址:https://www.cnblogs.com/multhree/p/10597780.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!