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

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

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

/**
 * struct TreeNode {
 *  int val;
 *  struct TreeNode *left;
 *  struct TreeNode *right;
 *  TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 二叉树的左节点、根节点和右节点是一个整体;
 叶子节点的特征是左右节点都为空;它是唯一的可能返回true的情况,其它情况,就是false啦;
 * };
 */
class Solution {
 public:
  bool hasPathSum(TreeNode* root, int sum) {
    if (root == nullptr)
        return false;

    sum -= root->val;
    if (root->left == nullptr && root->right == nullptr && sum == 0)
      return true;

    return hasPathSum(root->left, sum) || hasPathSum(root->right, sum);
  }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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