Diameter of a Binary Tree
Problem statement
Given the root of a binary tree, return its diameter: the maximum number of edges on a path between any two nodes.
The path may or may not pass through the root. Return 0 for an empty tree or a one-node tree.
Function
diameterOfBinaryTree(root: TreeNode) → intExamples
Example 1
root = [1,2,3,4,5]return = 3A longest path is 4 → 2 → 1 → 3, which contains three edges.
Example 2
root = [1,2]return = 1The only nonempty path between distinct nodes uses one edge.
Example 3
root = []return = 0An empty tree has no edges.
Constraints
- The tree contains between
0and100000nodes. -10^9 <= Node.val <= 10^9.- Node values do not affect the answer.