Height of Special Binary Tree - Problem

You are given a root, which is the root of a special binary tree with n nodes. The nodes of the special binary tree are numbered from 1 to n.

Suppose the tree has k leaves in the following order: b₁ < b₂ < ... < bₖ. The leaves of this tree have a special property:

  • For every leaf bᵢ, the right child of bᵢ is bᵢ + 1 if i < k, and b₁ otherwise.
  • For every leaf bᵢ, the left child of bᵢ is bᵢ - 1 if i > 1, and bₖ otherwise.

Return the height of the given tree.

Note: The height of a binary tree is the length of the longest path from the root to any other node.

Input & Output

Example 1 — Basic Binary Tree
$ Input: root = [3,9,20,null,null,15,7]
Output: 3
💡 Note: The longest path is from root to leaf: 3→20→15 or 3→20→7, both have length 3, so height is 3.
Example 2 — Simple Tree
$ Input: root = [1,2,3,4,5]
Output: 2
💡 Note: Tree has 3 levels (0,1,2). Longest path is 1→2→4 or 1→2→5, both have length 2.
Example 3 — Single Node
$ Input: root = [1]
Output: 0
💡 Note: Only root node exists, so height is 0 (no edges from root to itself).

Constraints

  • The number of nodes in the tree is in the range [1, 104]
  • -100 ≤ Node.val ≤ 100

Visualization

Tap to expand
Binary Tree Height Calculation3920157Path 1: Length 1Path 2: Length 2Path 3: Length 2Longest paths: 3→20→15 and 3→20→7 both have length 2Tree Height = 2Height FormulaMax depth fromroot to any leaf
Understanding the Visualization
1
Input Tree
Binary tree with nodes at different levels
2
Find Paths
Identify all root-to-leaf paths and measure lengths
3
Maximum Length
Height equals the length of longest path
Key Takeaway
🎯 Key Insight: Tree height is the maximum number of edges from root to the deepest leaf node
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
78.5K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen