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: 2
💡 Note: The longest path is from root to leaf: 3→20→15 or 3→20→7, both have length 2, so height is 2.
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
Height of Special Binary Tree INPUT Binary Tree Structure 3 9 20 15 7 d=0 d=1 d=2 Input Array: [3,9,20,null,null,15,7] Special Property: Leaves form circular links (shown as dashed red lines) ALGORITHM STEPS 1 Start DFS from root Initialize depth = 0 2 Check leaf nodes Detect circular links 3 Early Pruning Skip visited leaf links 4 Track max depth Return maximum height DFS Traversal 3 9 20 15 7 h=1 h=2 h=3 FINAL RESULT Tree Height Calculation 3 9 20 15 7 Height = 3 Output: 3 OK Height verified! Key Insight: In a special binary tree, leaf nodes form circular connections. The optimized DFS with early pruning avoids infinite loops by detecting when a child pointer leads back to another leaf node. Height is calculated as the longest path from root to any leaf, ignoring the special circular links. TutorialsPoint - Height of Special Binary Tree | Optimized DFS with Early Pruning
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