Diameter of Binary Tree Visualizer & Step-by-Step Algorithm Solution

Compute the diameter (longest path between any two nodes) by finding max(leftDepth + rightDepth) at each node using postorder DFS.

Category: trees | Difficulty: Easy

Tags: DFS, Binary Tree, Recursion, Tree Height, Path

Diameter of Binary Tree

1
2
4
5
3
100%
state
maxDiameter0
Initialization
1/28
Explanation

Start diameterOfBinaryTree on tree with root: Node(1).

Source Code
1function diameterOfBinaryTree(root) {
2 let maxDiameter = 0;
3 function dfs(node) {
4 if (!node) return 0;
5 const left = dfs(node.left);
6 const right = dfs(node.right);
7 maxDiameter = Math.max(maxDiameter, left + right);
8 return 1 + Math.max(left, right);
9 }
10 dfs(root);
11 return maxDiameter;
12}