|
| 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