-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConstruct Quad Tree.kt
66 lines (53 loc) · 1.45 KB
/
Construct Quad Tree.kt
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
/**
* Definition for a QuadTree node.
* class Node(var `val`: Boolean, var isLeaf: Boolean) {
* var topLeft: Node? = null
* var topRight: Node? = null
* var bottomLeft: Node? = null
* var bottomRight: Node? = null
* }
*/
class Solution {
private lateinit var grid: Array<IntArray>
fun construct(grid: Array<IntArray>): Node? {
this.grid = grid
return getNode(0, 0, grid.size)
}
private fun getNode(left: Int, top: Int, n: Int): Node? {
if (n == 0) {
return null
}
var sum = 0
for (i in top..(top+n-1)) {
for (j in left..(left+n-1)) {
sum += grid[i][j]
}
}
val isAllZero = sum == 0
val isAllOne = sum == (n*n)
val isLeaf = isAllZero || isAllOne
val halfSize = n / 2
return Node(isAllOne,isLeaf).apply {
topLeft = if (isLeaf) {
null
} else {
getNode(left, top, halfSize)
}
topRight = if (isLeaf) {
null
} else {
getNode(left + halfSize, top, halfSize)
}
bottomLeft = if (isLeaf) {
null
} else {
getNode(left, top + halfSize, halfSize)
}
bottomRight = if (isLeaf) {
null
} else {
getNode(left + halfSize, top + halfSize, halfSize)
}
}
}
}