Skip to content

112. Path Sum 👍

  • Time: $O(n)$
  • Space: $O(h)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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);
  }
}
1
2
3
4
5
6
7
8
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)