Leetcode

Path Sum

  • Time:O(n)
  • Space:O(h)

C++

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);
  }
};

JAVA

class Solution {
  public boolean hasPathSum(TreeNode root, int sum) {
    if (root == null)
      return false;
    if (root.val == sum && root.left == null && root.right == null)
      return true;
    return hasPathSum(root.left, sum - root.val) ||
           hasPathSum(root.right, sum - root.val);
  }
}

Python

class Solution:
  def hasPathSum(self, root: TreeNode, sum: int) -> bool:
    if not root:
      return False
    if root.val == sum and not root.left and not root.right:
      return True
    return self.hasPathSum(root.left, sum - root.val) or \
        self.hasPathSum(root.right, sum - root.val)