0
0
DSA Javascriptprogramming~5 mins

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

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

We want to understand how the time to explore a tree changes as the tree grows.

How does the number of steps grow when we visit nodes like root, leaves, or measure height and depth?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function treeHeight(node) {
  if (!node) return -1;
  const leftHeight = treeHeight(node.left);
  const rightHeight = treeHeight(node.right);
  return Math.max(leftHeight, rightHeight) + 1;
}
    

This code finds the height of a binary 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 height.

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

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

Final Time Complexity

Time Complexity: O(n)

This means the time to find 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 takes less time than visiting all nodes."

[OK] Correct: Even to find the longest path, the function must check every node to be sure no longer path exists.

Interview Connect

Understanding how tree operations scale helps you explain your approach clearly and confidently in interviews.

Self-Check

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