Height of Special Binary Tree Problem
Description
LeetCode Problem 2773.
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_1<b_2< ... < b_k.
The leaves of this tree have a special property! That is, for every leaf b_i, the following conditions hold:
- The right child of
b_iisb_(i + 1)ifi < k, andb_1otherwise. - The left child of
b_iisb_(i - 1)ifi > 1, andb_kotherwise.
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.
Example 1:
Input: root = [1,2,3,null,null,4,5]
Output: 2
Explanation: The given tree is shown in the following picture. Each leaf's left child is the leaf to its left (shown with the blue edges). Each leaf's right child is the leaf to its right (shown with the red edges). We can see that the graph has a height of 2.

Example 2:
Input: root = [1,2]
Output: 1
Explanation: The given tree is shown in the following picture. There is only one leaf, so it doesn't have any left or right child. We can see that the graph has a height of 1.

Example 3:
Input: root = [1,2,3,null,null,4,null,5,6]
Output: 3
Explanation: The given tree is shown in the following picture. Each leaf's left child is the leaf to its left (shown with the blue edges). Each leaf's right child is the leaf to its right (shown with the red edges). We can see that the graph has a height of 3.

Constraints:
n == number of nodes in the tree2 <= n <= 10^41 <= node.val <= n- The input is generated such that each
node.valis unique.
Solution
Approach: DFS
The leaves are linked through their left and right pointers, so a plain DFS would loop forever. The trick is to recognise those extra edges: a real child edge root -> root.left is skipped when root.left.right == root, because only a leaf's right pointer can point back at a leaf. The same goes for the right child with root.right.left == root.
Run dfs(root, d), record max(ans, d) at every visited node, and only follow the real child edges. The answer is the largest depth reached.
Complexity: O(n) time and O(n) space for the recursion.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def heightOfTree(self, root: Optional[TreeNode]) -> int:
def dfs(root: Optional[TreeNode], d: int):
nonlocal ans
ans = max(ans, d)
if root.left and root.left.right != root:
dfs(root.left, d + 1)
if root.right and root.right.left != root:
dfs(root.right, d + 1)
ans = 0
dfs(root, 0)
return ans