Binary Tree · Height

Height of Binary Tree

Compute maximum depth using recursive DFS and bottom-up subtree heights.

RecursionDFSTree DP Base

Key concepts at a glance — for those who already know the basics.

Problem Statement

Height (Maximum Depth) of Binary Tree

Given the root of a binary tree, return the maximum depth, which is the number of nodes on the longest root-to-leaf path.
Example 1

Input: [3,9,20,null,null,15,7]

Output: 3

Example 2

Input: [1,null,2]

Output: 2

Constraints

  • Nodes range: [0, 10^4]
  • Node values range: [-100, 100]
01

The Formula

height(node) = 1 + max(left, right)

Null node contributes 0 depth in node-count formulation.

02

How to Think

1

Go to leaves first

Leaves are smallest subproblems and return 1.

2

Return subtree height

Each call returns one integer to parent.

3

Take max of both sides

Longest branch determines depth at each node.

03

Code

solution.py
def maxDepth(root):
if root is None: return 0
left_height = maxDepth(root.left)
right_height = maxDepth(root.right)
return 1 + max(left_height, right_height)
04

Complexity

Time

O(n)

Visit each node exactly once.

Space

O(h)

Recursion stack equals tree height.

05

Interview Uses

Balanced Binary Tree

Compare left and right subtree heights at each node.

Diameter of Binary Tree

Use heights to compute longest path through each node.

Max Path / Tree DP

Height is a core subroutine in many tree DP problems.

Platform difference checks

Some sites ask node depth, others ask edge height.

Ready to watch recursion live?

Open the visualizer and follow how each node returns its subtree height.

Open Visualizer