Given the root of a binary tree, return the length of the diameter of the tree.
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.
The length of a path between two nodes is represented by the number of edges between them.
Example 1:
Input: root = [1,2,3,4,5]
Output: 3
Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].
Example 2:
Input: root = [1,2]
Output: 1
Constraints:
The number of nodes in the tree is in the range [1, 104].
-100 <= Node.val <= 100
Solutions
Solution 1: Enumeration + DFS
We can enumerate each node of the binary tree, and for each node, calculate the maximum depth of its left and right subtrees, \(\textit{l}\) and \(\textit{r}\), respectively. The diameter of the node is \(\textit{l} + \textit{r}\). The maximum diameter among all nodes is the diameter of the binary tree.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the number of nodes in the binary tree.
1 2 3 4 5 6 7 8 910111213141516171819
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:defdiameterOfBinaryTree(self,root:TreeNode)->int:defdfs(root):ifrootisNone:return0nonlocalansleft,right=dfs(root.left),dfs(root.right)ans=max(ans,left+right)return1+max(left,right)ans=0dfs(root)returnans
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcdiameterOfBinaryTree(root*TreeNode)(ansint){vardfsfunc(root*TreeNode)intdfs=func(root*TreeNode)int{ifroot==nil{return0}l,r:=dfs(root.Left),dfs(root.Right)ans=max(ans,l+r)return1+max(l,r)}dfs(root)return}