Height of Binary Tree
The height of a Binary Tree is an important property that tells us how tall the tree is. It is determined by the longest path from the root node to any leaf node. Understanding tree height helps us analyze tree performance, recursion depth, and the efficiency of operations such as searching and insertion. In this topic, we will learn how to calculate the height of a Binary Tree using recursion and iterative techniques.
1. What Is the Height of a Binary Tree?
The height of a Binary Tree is the length of the longest path from the root node to a leaf node.
A path is a sequence of connected nodes. The height depends on the maximum number of levels or edges along such a path.
Consider the following Binary Tree:
1
/ \
2 3
/ \
4 5
/
6
The longest path from the root node 1 to a leaf node is:
1 → 2 → 4 → 6
This path contains four nodes and three edges. Therefore:
- Height measured in nodes = 4
- Height measured in edges = 3
2. Understanding Height with Levels
A Binary Tree can be divided into levels. The root is generally considered to be at level 1 when counting levels from 1.
1 Level 1
/ \
2 3 Level 2
/ \
4 5 Level 3
/
6 Level 4
The longest root-to-leaf path reaches level 4. Therefore, the height measured in nodes is 4.
Height in nodes = Maximum number of levels = 4
Height in edges = 4 - 1 = 3
3. Important Cases of Tree Height
Case 1: Empty Tree
An empty tree does not contain any nodes. When height is measured in nodes, its height is 0.
Empty Tree
Height = 0
Case 2: Tree with Only One Node
If a tree contains only the root node, its height measured in nodes is 1.
10
Height = 1 node
Height = 0 edges
Case 3: Balanced Binary Tree
In a balanced tree, the left and right subtrees have similar heights. The tree does not become excessively tall compared with its number of nodes.
1
/ \
2 3
/ \ / \
4 5 6 7
Height = 3 nodes
Case 4: Skewed Binary Tree
A skewed Binary Tree is a tree in which every node has only one child, except the leaf node. It looks similar to a linked list.
1
\
2
\
3
\
4
Height = 4 nodes
Height = 3 edges
4. Formula to Calculate the Height of a Binary Tree
The height of a Binary Tree can be calculated using the heights of its left and right subtrees.
The recursive formula when height is measured in nodes is:
Height(root) = 0, if root is NULL
Height(root) = 1 + max(Height(left), Height(right))
Here:
- root: The current node.
- left: The left child of the current node.
- right: The right child of the current node.
- max(): Returns the larger of two values.
- 1: Counts the current node.
We calculate the height of both subtrees, select the larger height, and add 1 for the current node.
5. Recursive Approach to Find Height
Recursion is the simplest and most commonly used approach to calculate the height of a Binary Tree.
The basic idea is:
- If the current node is NULL, return 0.
- Calculate the height of the left subtree.
- Calculate the height of the right subtree.
- Find the maximum of the two heights.
- Add 1 for the current node and return the result.
C++ Code
#include <iostream>
#include <algorithm>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
Node(int value) {
data = value;
left = nullptr;
right = nullptr;
}
};
int height(Node* root) {
// Base case
if (root == nullptr) {
return 0;
}
// Calculate left subtree height
int leftHeight = height(root->left);
// Calculate right subtree height
int rightHeight = height(root->right);
// Return maximum height plus current node
return 1 + max(leftHeight, rightHeight);
}
int main() {
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->left->left->left = new Node(6);
cout << "Height of Binary Tree: "
<< height(root);
return 0;
}
Output
Height of Binary Tree: 4
Code Explanation
The function height()
receives the root node of the tree.
- If root is NULL, the function returns 0 because an empty tree has height 0.
- The function recursively calculates the height of the left subtree.
- It also calculates the height of the right subtree.
-
The
max()function selects the larger height. - Finally, 1 is added to count the current node.
6. Dry Run of Recursive Height Calculation
Consider this Binary Tree:
1
/ \
2 3
/ \
4 5
/
6
We begin at the root node 1. The function first explores the left subtree and then the right subtree.
Step-by-Step Calculation
- Node 6 has no children. Its height is 1.
- Node 4 has a left subtree of height 1 and an empty right subtree of height 0. Its height is 1 + max(1, 0) = 2.
- Node 5 is a leaf node. Its height is 1.
- Node 2 has left height 2 and right height 1. Its height is 1 + max(2, 1) = 3.
- Node 3 is a leaf node. Its height is 1.
- Node 1 has left height 3 and right height 1. Its height is 1 + max(3, 1) = 4.
| Node | Left Height | Right Height | Calculated Height |
|---|---|---|---|
| 6 | 0 | 0 | 1 |
| 4 | 1 | 0 | 2 |
| 5 | 0 | 0 | 1 |
| 2 | 2 | 1 | 3 |
| 3 | 0 | 0 | 1 |
| 1 | 3 | 1 | 4 |
Final Height = 4 nodes
7. Iterative Approach Using Level Order Traversal
We can also calculate the height of a Binary Tree without recursion by using a queue.
This approach uses Level Order Traversal. We process all nodes at one level before moving to the next level. Every time we finish processing a level, we increase the height by 1.
Algorithm
- If the root is NULL, return 0.
- Create an empty queue and insert the root node.
- Initialize height to 0.
- While the queue is not empty, find its current size.
- Process exactly that many nodes for the current level.
- Insert the left and right children if they exist.
- After processing the complete level, increase height by 1.
- Return height when the queue becomes empty.
C++ Code
#include <iostream>
#include <queue>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
Node(int value) {
data = value;
left = nullptr;
right = nullptr;
}
};
int heightIterative(Node* root) {
if (root == nullptr) {
return 0;
}
queue<Node*> q;
q.push(root);
int height = 0;
while (!q.empty()) {
int levelSize = q.size();
// Process all nodes at the current level
for (int i = 0; i < levelSize; i++) {
Node* current = q.front();
q.pop();
if (current->left != nullptr) {
q.push(current->left);
}
if (current->right != nullptr) {
q.push(current->right);
}
}
// One complete level has been processed
height++;
}
return height;
}
int main() {
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->left->left->left = new Node(6);
cout << "Height of Binary Tree: "
<< heightIterative(root);
return 0;
}
Output
Height of Binary Tree: 4
Dry Run of Iterative Approach
For the same tree:
1
/ \
2 3
/ \
4 5
/
6
| Level | Nodes Processed | Queue After Processing | Height |
|---|---|---|---|
| 1 | 1 | 2, 3 | 1 |
| 2 | 2, 3 | 4, 5 | 2 |
| 3 | 4, 5 | 6 | 3 |
| 4 | 6 | Empty | 4 |
Four levels are processed, so the height measured in nodes is 4.
8. Recursive vs Iterative Approach
| Feature | Recursive Approach | Iterative Approach |
|---|---|---|
| Technique | Recursion | Queue and Level Order Traversal |
| Time Complexity | O(N) | O(N) |
| Auxiliary Space | O(H) | O(W) |
| Implementation | Short and simple | Requires queue management |
| Useful For | Recursive tree problems | Level-based tree processing |
Here, N is the number of nodes, H is the height of the tree, and W is the maximum width of the tree.
9. Time and Space Complexity
Recursive Approach
Every node is visited exactly once to calculate its height. Therefore, the time complexity is O(N).
Time Complexity = O(N)
Auxiliary Space = O(H)
The recursive function uses the call stack. The maximum number of active recursive calls depends on the height of the tree.
- Balanced tree: O(log N) recursion stack space.
- Skewed tree: O(N) recursion stack space.
Iterative Approach
Every node is inserted into and removed from the queue once. Therefore, its time complexity is also O(N).
Time Complexity = O(N)
Auxiliary Space = O(W)
W represents the maximum number of nodes stored at one level of the tree. In the worst case, the queue may contain O(N) nodes.
10. Difference Between Depth and Height
Depth and height are related concepts, but they are not the same.
Depth of a Node
The depth of a node is the number of edges from the root node to that particular node.
Height of a Node
The height of a node is the number of edges on the longest downward path from that node to a leaf.
| Concept | Meaning |
|---|---|
| Depth | Distance from root to a particular node. |
| Height | Longest downward distance from a node to a leaf. |
| Tree Height | Height of the root node. |
11. Applications of Binary Tree Height
Finding the height of a Binary Tree is useful in many Data Structures and Algorithms problems.
- Tree Balancing: Height is used to check whether a Binary Tree is balanced.
- Binary Search Trees: The height helps understand the performance of searching, insertion, and deletion.
- Recursion Analysis: Height helps determine the maximum recursion depth.
- Tree Diameter: Height calculations are useful when finding the longest path between two nodes.
- Tree Optimization: Balanced trees aim to keep height small to improve operation efficiency.
12. Common Mistakes
- Forgetting the base case for a NULL node.
- Returning the smaller subtree height instead of the larger one.
- Forgetting to add 1 for the current node when using the node-count convention.
- Confusing height measured in nodes with height measured in edges.
- Assuming every Binary Tree is balanced.
- Forgetting that a skewed tree can have height O(N).
- In the iterative approach, increasing the height for every node instead of once per level.
13. Important Interview Questions
Q1. What is the height of a Binary Tree?
It is the length of the longest path from the root to a leaf node. It may be measured in nodes or edges depending on the convention.
Q2. What is the height of an empty tree?
When height is measured in nodes, an empty tree has height 0. When measured in edges, it is commonly defined as -1.
Q3. What is the height of a tree containing only one node?
Its height is 1 when measured in nodes and 0 when measured in edges.
Q4. What is the formula for calculating tree height?
Height(root) = 1 + max(Height(left), Height(right)), with height 0 for a NULL node under the node-count convention.
Q5. What is the time complexity of finding tree height?
O(N), because every node is visited once.
Q6. What is the auxiliary space complexity of recursive height calculation?
O(H), where H is the height of the tree, because of the recursive call stack.
Q7. Can we calculate height without recursion?
Yes. We can use a queue and Level Order Traversal to count the number of levels.
Q8. What is the maximum height of a Binary Tree with N nodes?
When measured in nodes, the maximum height is N. This occurs when the tree is completely skewed.
Q9. What is the minimum possible height of a Binary Tree with N nodes?
A tree with N nodes has minimum possible height when it is as complete and balanced as possible. Under the node-count convention, the minimum height is approximately log2(N + 1), rounded up.
Q10. Why is height important in a Binary Search Tree?
The height affects how many nodes may need to be visited during searching, insertion, and deletion. A smaller height generally allows these operations to be more efficient.
14. Practice Problems
- Write a recursive C++ program to find the height of a Binary Tree.
- Find the height of a tree containing only one node.
- Find the height of a completely skewed Binary Tree.
- Implement height calculation using a queue.
- Calculate the height of a given Binary Tree using a dry run.
- Explain the difference between height measured in nodes and edges.
- Find the maximum possible height of a Binary Tree containing N nodes.
- Analyze the time and space complexity of both approaches.
15. Summary
The height of a Binary Tree represents the length of its longest root-to-leaf path. It is an important property used in tree analysis and many interview problems.
- Height measured in nodes counts the nodes on the longest root-to-leaf path.
- Height measured in edges counts the connections on that path.
- Recursive calculation uses the maximum height of the left and right subtrees.
- Iterative calculation can be performed using a queue and Level Order Traversal.
- Both approaches take O(N) time.