0
0
DSA Goprogramming~5 mins

Height of Binary Tree in DSA Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Height of Binary Tree
O(n)
Understanding Time Complexity

We want to understand how long it takes to find the height of a binary tree as the tree grows bigger.

How does the time needed change when the tree has more nodes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


func height(root *Node) int {
  if root == nil {
    return 0
  }
  leftHeight := height(root.Left)
  rightHeight := height(root.Right)
  if leftHeight > rightHeight {
    return leftHeight + 1
  }
  return 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 number of nodes grows, the function visits each node once to calculate height.

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

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 should be O(log n)."

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

Interview Connect

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

Self-Check

"What if we stored the height at each node during insertion? How would the time complexity of finding height change?"