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 TreeThe 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
- If the current node is null, its height is -1 (or 0, depending on convention) — base case.
- Recursively compute the height of the left subtree.
- Recursively compute the height of the right subtree.
- Return 1 plus the larger of the two subtree heights.
Height Worked Example
Input: Tree: root(1) -> left(2) -> left(3); root -> right(4)
- Height of node 3 (leaf) = 0
- Height of node 2 = 1 + height(3) = 1
- Height of node 4 (leaf) = 0
- Height of root = 1 + max(height(2), height(4)) = 1 + max(1, 0) = 2
Output: 2
Press ▶ Run to watch it step by step.
def height(root):
if not root:
return -1 # empty tree height = -1
return 1 + max(height(root.left), height(root.right))
# example: heightBehind 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
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
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.