Skip to content

Latest commit

 

History

History
49 lines (34 loc) · 1.44 KB

0112.md

File metadata and controls

49 lines (34 loc) · 1.44 KB

Level: Easy

Topic: Tree Binary Tree Depth First Search Breadth First Search

Question

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: The root-to-leaf path with the target sum is shown.

Intuition

Recursive:

  • if current node is null, meaning it didn't find the path sum so it reaches the null leaf
  • when it's the leaf node, check if there exists a path sum
    • sum == 0, means all values in that path has been summed up to targetSum
  • tree traversal with the deduction of current node val from targetSum

Code

Time: O(n)
Space: O(n)

Recursive

public boolean hasPathSum(TreeNode root, int targetSum) {
    if (root == null)
        return false;

    targetSum -= root.val;
    if (root.left == null && root.right == null)
        return targetSum == 0;

    return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum);
}