Skip to content

Commit 0faee22

Browse files
committed
Add solution #1245
1 parent 8f413cd commit 0faee22

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1155,6 +1155,7 @@
11551155
1240|[Tiling a Rectangle with the Fewest Squares](./solutions/1240-tiling-a-rectangle-with-the-fewest-squares.js)|Hard|
11561156
1243|[Array Transformation](./solutions/1243-array-transformation.js)|Easy|
11571157
1244|[Design A Leaderboard](./solutions/1244-design-a-leaderboard.js)|Medium|
1158+
1245|[Tree Diameter](./solutions/1245-tree-diameter.js)|Medium|
11581159
1247|[Minimum Swaps to Make Strings Equal](./solutions/1247-minimum-swaps-to-make-strings-equal.js)|Medium|
11591160
1248|[Count Number of Nice Subarrays](./solutions/1248-count-number-of-nice-subarrays.js)|Medium|
11601161
1249|[Minimum Remove to Make Valid Parentheses](./solutions/1249-minimum-remove-to-make-valid-parentheses.js)|Medium|

solutions/1245-tree-diameter.js

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/**
2+
* 1245. Tree Diameter
3+
* https://leetcode.com/problems/tree-diameter/
4+
* Difficulty: Medium
5+
*
6+
* The diameter of a tree is the number of edges in the longest path in that tree.
7+
*
8+
* There is an undirected tree of n nodes labeled from 0 to n - 1. You are given a 2D array
9+
* edges where edges.length == n - 1 and edges[i] = [ai, bi] indicates that there is an
10+
* undirected edge between nodes ai and bi in the tree.
11+
*
12+
* Return the diameter of the tree.
13+
*/
14+
15+
/**
16+
* @param {number[][]} edges
17+
* @return {number}
18+
*/
19+
var treeDiameter = function(edges) {
20+
if (edges.length === 0) return 0;
21+
22+
const graph = new Map();
23+
for (const [a, b] of edges) {
24+
if (!graph.has(a)) graph.set(a, []);
25+
if (!graph.has(b)) graph.set(b, []);
26+
graph.get(a).push(b);
27+
graph.get(b).push(a);
28+
}
29+
30+
const [farthestFromStart] = bfs(0);
31+
const [, diameter] = bfs(farthestFromStart);
32+
33+
return diameter;
34+
35+
function bfs(start) {
36+
const visited = new Set();
37+
const queue = [[start, 0]];
38+
visited.add(start);
39+
let farthestNode = start;
40+
let maxDistance = 0;
41+
42+
while (queue.length > 0) {
43+
const [node, distance] = queue.shift();
44+
45+
if (distance > maxDistance) {
46+
maxDistance = distance;
47+
farthestNode = node;
48+
}
49+
50+
for (const neighbor of graph.get(node) || []) {
51+
if (!visited.has(neighbor)) {
52+
visited.add(neighbor);
53+
queue.push([neighbor, distance + 1]);
54+
}
55+
}
56+
}
57+
58+
return [farthestNode, maxDistance];
59+
}
60+
};

0 commit comments

Comments
 (0)