Path Sum — Root-to-Leaf DFS with Running Remainder
Advertisement
Problem 350 · Path Sum
Difficulty: Easy · Pattern: Path Sum DFS
Solutions
# Python
def hasPathSum(root, target):
if not root: return False
if not root.left and not root.right: return root.val == target
return hasPathSum(root.left, target-root.val) or hasPathSum(root.right, target-root.val)
// Java
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root==null) return false;
if (root.left==null&&root.right==null) return root.val==targetSum;
return hasPathSum(root.left,targetSum-root.val)||hasPathSum(root.right,targetSum-root.val);
}
Complexity
- Time: O(n)
- Space: O(h)
Advertisement