Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 1e37749

Browse files
committed
Add solution #310
1 parent 41b6520 commit 1e37749

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

0310-minimum-height-trees.js

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* 310. Minimum Height Trees
3+
* https://leetcode.com/problems/minimum-height-trees/
4+
* Difficulty: Medium
5+
*
6+
* A tree is an undirected graph in which any two vertices are connected by exactly one
7+
* path. In other words, any connected graph without simple cycles is a tree.
8+
*
9+
* Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where
10+
* edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes
11+
* ai and bi in the tree, you can choose any node of the tree as the root. When you select
12+
* a node x as the root, the result tree has height h. Among all possible rooted trees,
13+
* those with minimum height (i.e. min(h)) are called minimum height trees (MHTs).
14+
*
15+
* Return a list of all MHTs' root labels. You can return the answer in any order.
16+
*
17+
* The height of a rooted tree is the number of edges on the longest downward path
18+
* between the root and a leaf.
19+
*/
20+
21+
/**
22+
* @param {number} n
23+
* @param {number[][]} edges
24+
* @return {number[]}
25+
*/
26+
var findMinHeightTrees = function(n, edges) {
27+
if (n === 1) return [0];
28+
29+
const lookup = new Array(n).fill().map(() => new Set());
30+
for (const [a, b] of edges) {
31+
lookup[a].add(b);
32+
lookup[b].add(a);
33+
}
34+
35+
let result = [];
36+
for (let i = 0; i < n; i++) {
37+
if (lookup[i].size === 1) result.push(i);
38+
}
39+
40+
while (n > 2) {
41+
n -= result.length;
42+
const modified = [];
43+
for (const item of result) {
44+
const adj = lookup[item].values().next().value;
45+
lookup[adj].delete(item);
46+
if (lookup[adj].size === 1) {
47+
modified.push(adj);
48+
}
49+
}
50+
result = modified;
51+
}
52+
53+
return result;
54+
};

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,7 @@
252252
306|[Additive Number](./0306-additive-number.js)|Medium|
253253
307|[Range Sum Query - Mutable](./0307-range-sum-query-mutable.js)|Medium|
254254
309|[Best Time to Buy and Sell Stock with Cooldown](./0309-best-time-to-buy-and-sell-stock-with-cooldown.js)|Medium|
255+
310|[Minimum Height Trees](./0310-minimum-height-trees.js)|Medium|
255256
315|[Count of Smaller Numbers After Self](./0315-count-of-smaller-numbers-after-self.js)|Hard|
256257
316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium|
257258
318|[Maximum Product of Word Lengths](./0318-maximum-product-of-word-lengths.js)|Medium|

0 commit comments

Comments
 (0)