0
0
DSA C++programming~5 mins

Height of Binary Tree in DSA C++ - 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.

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

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


int height(Node* root) {
  if (root == nullptr) return 0;
  int leftHeight = height(root->left);
  int rightHeight = height(root->right);
  return 1 + (leftHeight > rightHeight ? leftHeight : rightHeight);
}
    

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

Each node is visited once, so the time grows directly with the number of nodes.

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

Pattern observation: The time grows linearly as the tree size increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to find the height grows in direct proportion to the number of nodes in the tree.

Common Mistake

[X] Wrong: "The height calculation only depends on the longest path, so it should be faster than visiting all nodes."

[OK] Correct: To find the longest path, the function must check every node to be sure no taller path exists, so it visits 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 the tree was a balanced binary tree? How would the time complexity change?"