-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0427-construct-quad-tree.java
42 lines (33 loc) · 1.02 KB
/
0427-construct-quad-tree.java
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
class Solution {
private int[][] grid;
public Node construct(int[][] grid) {
this.grid = grid;
return dfs(0, 0, grid.length);
}
private Node dfs(int row, int column, int n) {
Node node = new Node();
if (areAllEqual(row, column, n)) {
node.isLeaf = true;
node.val = grid[row][column] == 1;
} else {
n /= 2;
node.isLeaf = false;
node.val = false;
node.topLeft = dfs(row, column, n);
node.bottomLeft = dfs(row + n, column, n);
node.topRight = dfs(row, column + n, n);
node.bottomRight = dfs(row + n, column + n, n);
}
return node;
}
private boolean areAllEqual(int row, int column, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (grid[row][column] != grid[row + i][column + j]) {
return false;
}
}
}
return true;
}
}