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

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

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

DFS。。。

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum) {
      if (root == nullptr) {
        return false;
      }
      
        //  一个结点和对应的路径累加和
      std::stack<std::pair<TreeNode *, int>> stack_;
      
      stack_.push({root, root->val});
      
      while (!stack_.empty()) {
        auto tmp = stack_.top();
        stack_.pop();
        
        if (tmp.first->left == nullptr && 
            tmp.first->right == nullptr &&
            tmp.second == sum) {
          return true;
        }
        
        if (tmp.first->left) {
          stack_.push({tmp.first->left, tmp.second + tmp.first->left->val});
        }
        if (tmp.first->right) {
          stack_.push({tmp.first->right, tmp.second + tmp.first->right->val});
        }
      }
      
      return false;
    }
};

递归求解:

class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum) {
      if (root == nullptr) {
        return false;
      }
      if (root->left == nullptr &&
          root->right == nullptr &&
          root->val - sum == 0) {
        return true;
      }
      
      return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
    }
};
全部评论

相关推荐

04-06 11:24
已编辑
太原学院 测试工程师
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务