Solution: Diameter of Binary Tree
Explore how to calculate the diameter of a binary tree by applying depth-first search. Understand both naive and optimized approaches, assess edge cases where the longest path includes or excludes the root, and learn to implement an efficient recursive solution that visits each node once for an O(n) time complexity.
Statement
Given a binary tree, you need to compute the length of the tree’s diameter. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Note: The length of the path between two nodes is represented by the number of edges between them.
Constraints:
- The number of nodes in the tree is in the range .