0
0
DSA Typescriptprogramming~5 mins

Tree Terminology Root Leaf Height Depth Level in DSA Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Tree Terminology Root Leaf Height Depth Level
O(n)
Understanding Time Complexity

When working with trees, it is important to understand how the time to visit nodes grows as the tree gets bigger.

We want to know how operations like finding height or depth take longer as the tree size increases.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function treeHeight(node: TreeNode | null): number {
  if (node === null) return -1;
  const leftHeight = treeHeight(node.left);
  const rightHeight = treeHeight(node.right);
  return 1 + Math.max(leftHeight, rightHeight);
}
    

This code calculates the height of a tree by checking the height of 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: Once per node in the tree.
How Execution Grows With Input

As the tree grows, the function visits every node once to find the height.

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

Pattern observation: The number of operations grows directly with the number of nodes.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "The height calculation only depends on the longest path, so it is constant time."

[OK] Correct: Even though height is about the longest path, the function must check every node to be sure, so it visits all nodes.

Interview Connect

Understanding how tree operations scale helps you explain your approach clearly and shows you know how data size affects performance.

Self-Check

"What if we changed the tree to be a linked list (all nodes have only one child)? How would the time complexity change?"