-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.js
74 lines (65 loc) · 1.87 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// URL: https://leetcode.com/problems/construct-quad-tree/
/**
* // Definition for a QuadTree node.
* function Node(val,isLeaf,topLeft,topRight,bottomLeft,bottomRight) {
* this.val = val;
* this.isLeaf = isLeaf;
* this.topLeft = topLeft;
* this.topRight = topRight;
* this.bottomLeft = bottomLeft;
* this.bottomRight = bottomRight;
* };
*/
class Node {
constructor(val, isLeaf, topLeft, topRight, bottomLeft, bottomRight) {
this.val = val;
this.isLeaf = isLeaf;
this.topLeft = topLeft;
this.topRight = topRight;
this.bottomLeft = bottomLeft;
this.bottomRight = bottomRight;
}
}
/**
* @param {number[][]} grid
* @return {Node}
*/
var construct = function (grid) {
function helper(fromI, fromJ, subsize) {
if (subsize === 1) {
const val = grid[fromI][fromJ];
return new Node(val, true, null, null, null, null);
}
let result = new Node(false, false, null, null, null, null);
const halfSize = subsize / 2;
let srTopLeft = helper(fromI, fromJ, halfSize);
let srTopRight = helper(fromI, halfSize + fromJ, halfSize);
let srBottomLeft = helper(halfSize + fromI, fromJ, halfSize);
let srBottomRight = helper(halfSize + fromI, halfSize + fromJ, halfSize);
if (
srTopLeft.isLeaf &&
srTopRight.isLeaf &&
srBottomLeft.isLeaf &&
srBottomRight.isLeaf
) {
if (
srTopLeft.val === srTopRight.val &&
srTopLeft.val === srBottomLeft.val &&
srTopLeft.val === srBottomRight.val
) {
result.val = srTopLeft.val;
result.isLeaf = true;
}
}
if (!result.isLeaf) {
result.topLeft = srTopLeft;
result.topRight = srTopRight;
result.bottomLeft = srBottomLeft;
result.bottomRight = srBottomRight;
}
return result;
}
const size = grid.length;
let result = helper(0, 0, size);
return result;
};