543. Diameter of Binary Tree
Asked at 19Meta88Amazon52Google44Bloomberg44Microsoft43Apple22Roblox62tcs42Wix87Nutanix71Verkada60Oracle52Palo Alto Networks50Flipkart43Walmart Labs43Nvidia39DE Shaw38DoorDash29TikTok26
Problem
Return the diameter of a binary tree: the number of edges on the longest path between any two nodes. The path doesn't have to pass through the root.
Example: [1,2,3,4,5] → 3 (path 4 → 2 → 1 → 3)
The longest path through a node = height(left) + height(right). Return height upward, update a global best on the way.
Complexity: O(n).
class Solution:
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
best = 0
def height(node):
nonlocal best
if not node:
return 0
l, r = height(node.left), height(node.right)
best = max(best, l + r)
return 1 + max(l, r)
height(root)
return best
assert Solution().diameterOfBinaryTree(make_tree([1, 2, 3, 4, 5])) == 3
assert Solution().diameterOfBinaryTree(make_tree([1, 2])) == 1
class Solution {
private int best = 0;
public int diameterOfBinaryTree(TreeNode root) {
height(root);
return best;
}
private int height(TreeNode n) {
if (n == null) return 0;
int l = height(n.left), r = height(n.right);
best = Math.max(best, l + r);
return 1 + Math.max(l, r);
}
}
func diameterOfBinaryTree(root *TreeNode) int {
best := 0
var height func(*TreeNode) int
height = func(node *TreeNode) int {
if node == nil {
return 0
}
l, r := height(node.Left), height(node.Right)
best = max(best, l+r) // longest path through node
return 1 + max(l, r)
}
height(root)
return best
}