Return the diameter of a binary tree: the number of edges on the longest path between any two nodes. The path may or may not pass through the root.
A post-order DFS returns each subtree's depth. On the way up, update the best diameter with left + right at that node.
1function diameterOfBinaryTree(root: TreeNode | null): number {2let best = 0;3function dfs(n: TreeNode | null): number {4if (!n) return 0;5const l = dfs(n.left), r = dfs(n.right);6best = Math.max(best, l + r);7return 1 + Math.max(l, r);8}9dfs(root);10return best;11}
best = 0.
Space: play/pause · ←/→: step