Skip to content

Commit d6915b6

Browse files
committedFeb 26, 2025
Add solution #427
1 parent bbd06a0 commit d6915b6

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -339,6 +339,7 @@
339339
421|[Maximum XOR of Two Numbers in an Array](./0421-maximum-xor-of-two-numbers-in-an-array.js)|Medium|
340340
423|[Reconstruct Original Digits from English](./0423-reconstruct-original-digits-from-english.js)|Medium|
341341
424|[Longest Repeating Character Replacement](./0424-longest-repeating-character-replacement.js)|Medium|
342+
427|[Construct Quad Tree](./0427-construct-quad-tree.js)|Medium|
342343
434|[Number of Segments in a String](./0434-number-of-segments-in-a-string.js)|Easy|
343344
435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium|
344345
437|[Path Sum III](./0437-path-sum-iii.js)|Medium|

‎solutions/0427-construct-quad-tree.js

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* 427. Construct Quad Tree
3+
* https://leetcode.com/problems/construct-quad-tree/
4+
* Difficulty: Medium
5+
*
6+
* Given a n * n matrix grid of 0's and 1's only. We want to represent grid with a Quad-Tree.
7+
*
8+
* Return the root of the Quad-Tree representing grid.
9+
*
10+
* A Quad-Tree is a tree data structure in which each internal node has exactly four children.
11+
* Besides, each node has two attributes:
12+
* - val: True if the node represents a grid of 1's or False if the node represents a grid of
13+
* 0's. Notice that you can assign the val to True or False when isLeaf is False, and both are
14+
* accepted in the answer.
15+
* - isLeaf: True if the node is a leaf node on the tree or False if the node has four children.
16+
*/
17+
18+
/**
19+
* // Definition for a QuadTree node.
20+
* function _Node(val,isLeaf,topLeft,topRight,bottomLeft,bottomRight) {
21+
* this.val = val;
22+
* this.isLeaf = isLeaf;
23+
* this.topLeft = topLeft;
24+
* this.topRight = topRight;
25+
* this.bottomLeft = bottomLeft;
26+
* this.bottomRight = bottomRight;
27+
* };
28+
*/
29+
30+
/**
31+
* @param {number[][]} grid
32+
* @return {_Node}
33+
*/
34+
var construct = function(grid) {
35+
return build(0, 0, grid.length);
36+
37+
function build(x, y, n) {
38+
const value = grid[x][y];
39+
for (let i = x; i < x + n; i++) {
40+
for (let j = y; j < y + n; j++) {
41+
if (grid[i][j] !== value) {
42+
n /= 2;
43+
return new _Node(true, false,
44+
build(x, y, n),
45+
build(x, y + n, n),
46+
build(x + n, y, n),
47+
build(x + n, y + n, n)
48+
);
49+
}
50+
}
51+
}
52+
return new _Node(value === 1, true, null, null, null, null);
53+
}
54+
};

0 commit comments

Comments
 (0)
Please sign in to comment.