Problem 149
Diameter of Binary Tree
Easy · 10 pts · Tree, Depth-First Search, Binary Tree
Problem
The diameter of a binary tree is the length of the longest path between any two nodes, measured as the number of edges on the path. The path does not have to pass through the root. Print the diameter of the given tree; a single node has diameter 0. The longest path through a node goes down into its left subtree and down into its right subtree, so its length is the height of the left subtree plus the height of the right subtree. Compute heights recursively and track the best sum seen at any node.
Input
First line: integer N, the number of tokens. Second line: N tokens describing the tree in level order, where 'null' marks a missing child (the same format LeetCode uses).
Output
Print the diameter.
Constraints
1 <= number of nodes <= 10000; -100 <= value <= 100
Example input
5 1 2 3 4 5
Example output
3
Explanation
The root 1 has children 2 and 3, and 2 has children 4 and 5. The path 4 → 2 → 1 → 3 uses 3 edges, and no path is longer, so the diameter is 3.