const tree = {
0: [1, 2],
1: [0, 3],
2: [0],
3: [1]
};
let diameter = 0;
function dfs(node, parent) {
let max1 = 0, max2 = 0;
for (const child of tree[node]) {
if (child === parent) continue;
const depth = dfs(child, node) + 1;
if (depth > max1) {
max2 = max1;
max1 = depth;
} else if (depth > max2) {
max2 = depth;
}
}
diameter = Math.max(diameter, max1 + max2);
return max1;
}
dfs(0, -1);
console.log(diameter);The diameter is the longest path between any two nodes. Here, the longest path is from node 3 to node 2 through nodes 1 and 0, which has length 3 edges.
The diameter can be the longest path passing through a node connecting two deepest subtrees. So, summing the two largest depths from children at that node gives a candidate diameter.
const tree = {
0: [1],
1: [0, 2],
2: [1]
};
let diameter = 0;
function dfs(node, parent) {
let max1 = 0, max2 = 0;
for (const child of tree[node]) {
if (child === parent) continue;
const depth = dfs(child, node) + 1;
if (depth > max1) {
max2 = max1;
max1 = depth;
} else if (depth > max2) {
max2 = depth;
}
}
diameter = Math.max(diameter, max1 + max2);
return max1;
}
dfs(0, -1);
console.log(diameter);The tree is a chain of 3 nodes (0-1-2). The longest path length is 2 edges. The code correctly calculates and outputs 2.
const tree = {
0: [1, 2],
1: [0, 3, 4],
2: [0],
3: [1, 5],
4: [1],
5: [3]
};
let diameter = 0;
function dfs(node, parent) {
let max1 = 0, max2 = 0;
for (const child of tree[node]) {
if (child === parent) continue;
const depth = dfs(child, node) + 1;
if (depth > max1) {
max2 = max1;
max1 = depth;
} else if (depth > max2) {
max2 = depth;
}
}
diameter = Math.max(diameter, max1 + max2);
return max1;
}
dfs(0, -1);
console.log(diameter);The longest path is from node 5 to node 2 through nodes 3, 1, and 0, which has length 4 edges.
The two DFS method first finds the farthest node from an arbitrary node, then runs DFS from that farthest node to find the longest path, which is the diameter.
