AlgoFrames

Height of a tree

Standard · Write code · about 10 min

Return the height of the binary tree with the given root. The height is the number of nodes on the longest path from the root down to a leaf. An empty tree has height 0 and a single node has height 1.

Example 1

Input:

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

Output:

3

The longest path is 3, 20, 15 (or 3, 20, 7).

Example 2

Input:

[[1,null,2]]

Output:

2

Two nodes in a chain.

Constraints

  • 0 ≤ number of nodes ≤ 1,000
  • -1,000 ≤ node value ≤ 1,000
  • The tree is given in level order; null marks a missing child

Learn the idea first: Why balance matters, a visual lesson.

More Why balance matters problems