Given the root of a binary tree, find its diameter. The diameter of a tree is defined as the number of edges in the longest path between any two nodes.
Examples:
Input: The binary tree for this example is shown in the image below.
[Naive Approach] By Calculating Height For Each Node - O(n2) Time and O(h) Space
The core idea involves recursively traversing the tree. At each node, we determine the heights of its left and right subtrees and update the maximum diameter by calculating the sum of these heights.
Output
4
[Expected Approach] Using Single Traversal - O(n) Time and O(h) Space
The core idea is to efficiently calculate the diameter, avoiding redundant height calculations. We use recursion to find both height and diameter in a single traversal. For each node, the longest path through it is the sum of its left and right subtree heights. By tracking the maximum diameter, we find the longest path.