Height of a binary tree
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Overview
A binary tree is a fundamental data structure in computer science, and understanding its properties such as height is crucial for analyzing algorithms that traverse or manipulate trees. The height of a binary tree is one of its most important characteristics, influencing both its structure and performance.
Definition of Height
The height of a binary tree is defined as the number of edges on the longest path from the root node to a leaf node. It can also be described in terms of the levels of the tree. The root node is at level 0, and the height is the level of the deepest leaf node.
Examples
- Single Node Tree:
- A tree consisting of a single root node has a height of 0 since the root itself is a leaf and there are no edges.
- Balanced Binary Tree:
- Consider a perfectly balanced binary tree with three levels. Each level is fully filled, resulting in a height of 2.
- Skewed Binary Tree:
- A skewed binary tree where each node has only one child can be more like a linear chain, resulting in the height being equal to the number of nodes minus one.
Calculating Height
The height of a binary tree can be calculated using recursive or iterative methods. A popular approach involves a recursive depth-first search (DFS).
Recursive Algorithm
Here is a simple recursive algorithm in Python to compute the height of a binary tree:
- Balanced Trees: Trees such as AVL or Red-Black trees are self-balancing and maintain a low height for performance close to `O(log n)`.
- Degenerate Trees: A degenerate (or pathological) tree acts like a linked list (skewed), resulting in a height of `n-1` which gives poor performance of `O(n)`.
Related reading
- Help me understand Inorder Traversal without using recursion
- Help with big O notation
- Helper library for distributed algorithms programming?
- Hexagonal Grids, how do you find which hexagon a point is in?
- helm error when updating UPGRADE FAILED The order in patch list
- Help Understanding Cross Validation and Decision Trees
- Hidden Markov Models with C
- Hierarchical clustering of 1 million objects

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.