Data Structures · Visualization

Binary Tree: Height

Binary Tree

The height of a tree is the number of edges on the longest path from the root down to a leaf (some definitions count nodes instead of edges — be consistent). Time: O(n) — every node is visited once. Space: O(h) for the recursion stack.

Big-O: Traversals visit every node exactly once: O(n).

Binary Tree: Height

Binary Tree

The height of a tree is the number of edges on the longest path from the root down to a leaf (some definitions count nodes instead of edges — be consistent). It is computed recursively: the height of a tree is one more than the taller of its two subtrees' heights.

How Height Works

  1. If the current node is null, its height is -1 (or 0, depending on convention) — base case.
  2. Recursively compute the height of the left subtree.
  3. Recursively compute the height of the right subtree.
  4. Return 1 plus the larger of the two subtree heights.

Height Worked Example

Input: Tree: root(1) -> left(2) -> left(3); root -> right(4)

  1. Height of node 3 (leaf) = 0
  2. Height of node 2 = 1 + height(3) = 1
  3. Height of node 4 (leaf) = 0
  4. Height of root = 1 + max(height(2), height(4)) = 1 + max(1, 0) = 2

Output: 2

Binary Tree: Introduction
A hierarchy of nodes where each node has at most two children — usually called "left" and "right".
45
20
10
30
40
65
50
60
70
80
Active Result
Binary Tree: Introduction
Press ▶ Run to watch it step by step.
Python · Binary Trees in Code
def height(root):
    if not root:
        return -1            # empty tree height = -1
    return 1 + max(height(root.left), height(root.right))
# example: height
Input: Tree: root(1) -> left(2) -> left(3); root -> right(4)

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Height Time & Space Complexity

TimeO(n) — every node is visited once
SpaceO(h) for the recursion stack

When to Use Height

  • Checking whether a tree is balanced (comparing subtree heights)
  • Estimating the worst-case time for tree operations, since many depend on height
  • Visualizing or laying out a tree for display

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.