binary tree
tree height
data structures
algorithm
computer science

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.

Practice algorithms

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

  1. 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.
  2. Balanced Binary Tree:
    • Consider a perfectly balanced binary tree with three levels. Each level is fully filled, resulting in a height of 2.
  3. 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
Course
Intermediate
27 lessons
15 hours
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 course
Track 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.

Practice algorithms

All Rights Reserved.