0
0
DSA Typescriptprogramming~5 mins

Path Sum Root to Leaf in Binary Tree in DSA Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Path Sum Root to Leaf in Binary Tree
O(n)
Understanding Time Complexity

We want to know how long it takes to check if a path from the root to any leaf adds up to a target sum in a binary tree.

How does the time needed grow as the tree gets bigger?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function hasPathSum(root: TreeNode | null, targetSum: number): boolean {
  if (!root) return false;
  if (!root.left && !root.right) return root.val === targetSum;
  return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
}
    

This code checks if there is any root-to-leaf path where the sum of node values equals the target sum.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Recursive calls visiting each node once.
  • How many times: Each node is visited once in the worst case.
How Execution Grows With Input

As the number of nodes grows, the function checks each node once to find paths.

Input Size (n)Approx. Operations
10About 10 node visits
100About 100 node visits
1000About 1000 node visits

Pattern observation: The operations grow roughly in direct proportion to the number of nodes.

Final Time Complexity

Time Complexity: O(n)

This means the time needed grows linearly with the number of nodes in the tree.

Common Mistake

[X] Wrong: "The function only checks one path, so it runs in constant time."

[OK] Correct: The function explores all possible paths to leaves, so it must visit every node in the worst case.

Interview Connect

Understanding this helps you explain how recursive tree traversal works and how to analyze its cost, a common skill in interviews.

Self-Check

"What if the tree was a linked list (each node has only one child)? How would the time complexity change?"