Diameter of a Binary Tree
Problem statement
Given the root of a binary tree, return its diameter: the largest number of edges on a path between any two nodes. The path may pass through the root, but does not have to.
Function
diameterOfBinaryTree(root: TreeNode) → intExamples
Example 1
root = [1,2,3,4,5]return = 3The path from node 4 through nodes 2 and 1 to node 3 has three edges.
Example 2
root = [1,2]return = 1The only path between the two nodes uses one edge.
Example 3
root = [7]return = 0A one-node tree has no edge.
Example 4
root = [1,2,3,4,null,null,5,6]return = 5The longest path runs from node 6 through nodes 4, 2, 1, and 3 to node 5.
Constraints
- The tree contains between
1and10000nodes. - Each node value is an integer between
-100and100.