0
0
DSA Typescriptprogramming~5 mins

Lowest Common Ancestor in Binary Tree in DSA Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Lowest Common Ancestor in Binary Tree
O(n)
Understanding Time Complexity

We want to understand how the time needed to find the lowest common ancestor changes as the tree grows.

How does the search through the tree affect the time taken?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function lowestCommonAncestor(root: TreeNode | null, p: TreeNode, q: TreeNode): TreeNode | null {
  if (!root || root === p || root === q) return root;
  const left = lowestCommonAncestor(root.left, p, q);
  const right = lowestCommonAncestor(root.right, p, q);
  if (left && right) return root;
  return left ? left : right;
}
    

This code finds the lowest common ancestor of two nodes in a binary tree by searching left and right subtrees recursively.

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 during the recursion.
How Execution Grows With Input

As the number of nodes in the tree grows, the function visits each node once to check for matches.

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

Pattern observation: The time grows roughly in direct proportion to the number of nodes.

Final Time Complexity

Time Complexity: O(n)

This means the time to find the ancestor grows linearly with the number of nodes in the tree.

Common Mistake

[X] Wrong: "The function only searches part of the tree, so it runs faster than visiting all nodes."

[OK] Correct: The function may need to visit every node in the worst case to find both targets, so it checks the whole tree.

Interview Connect

Understanding this helps you explain how recursive tree searches work and why visiting all nodes is sometimes necessary.

Self-Check

"What if the tree was a binary search tree? How would that change the time complexity?"