Height of Special Binary Tree - Problem

You are given a special binary tree with a fascinating structure! This isn't your ordinary binary tree - it has a unique property that creates connections between its leaves.

Here's how it works:

  • The tree has n nodes numbered from 1 to n
  • The tree has k leaves arranged in order: b₁ < b₂ < ... < bₖ
  • Special Property: Each leaf bᵢ has children that reference other leaves:
    • Right child: bᵢ₊₁ if i < k, otherwise b₁ (wraps around)
    • Left child: bᵢ₋₁ if i > 1, otherwise bₖ (wraps around)

Your task is to find the height of this tree - the length of the longest path from the root to any node.

Note: The height is measured as the number of edges in the longest path, not the number of nodes.

Input & Output

example_1.py — Simple Special Tree
$ Input: root = [1,2,3,4,5,null,null,null,null,null,null] Leaves: [4,5] where 4->right=5, 5->right=4, 4->left=5, 5->left=4
Output: 3
💡 Note: The longest path is from root(1) -> node(2) -> node(4) -> node(5), which has 3 edges, so height is 3.
example_2.py — Single Node Tree
$ Input: root = [1] Leaves: [1] where 1->right=1, 1->left=1
Output: 1
💡 Note: The tree has only one node which references itself. The path from root to itself through children has length 1.
example_3.py — Linear Tree
$ Input: root = [1,2,null,3,null,null,null] Leaves: [3] where 3->right=3, 3->left=3
Output: 3
💡 Note: The path is root(1) -> node(2) -> node(3) -> node(3), giving height 3.

Constraints

  • 1 ≤ n ≤ 104 (number of nodes)
  • 1 ≤ Node.val ≤ n
  • All node values are unique
  • The tree follows the special property described
  • The root is guaranteed to exist

Visualization

Tap to expand
ROOT23L1L2Circular ReferencesPath CalculationRoot → 2 → L1 → L2Height = 3 edges✓ Visited tracking prevents infinite loops in circular leaf referencesRed arrows show special leaf property: each leaf references adjacent leaves in circular pattern
Understanding the Visualization
1
Identify Tree Structure
Recognize the main tree structure and identify which nodes are leaves
2
Handle Circular References
Use visited tracking to avoid infinite loops when following leaf connections
3
Calculate Maximum Depth
Find the longest path from root to any reachable node using DFS
4
Return Height
Return the maximum depth found, representing the tree's height
Key Takeaway
🎯 Key Insight: The special property creates circular references between leaves, requiring cycle detection during traversal to find the true maximum depth without infinite loops.
Asked in
Google 15 Meta 12 Amazon 8 Microsoft 6
24.7K Views
Medium Frequency
~25 min Avg. Time
892 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