-
Notifications
You must be signed in to change notification settings - Fork 0
/
Construct Quad Tree
67 lines (60 loc) Β· 1.68 KB
/
Construct Quad Tree
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
/*
// Definition for a QuadTree node.
class Node {
public:
bool val;
bool isLeaf;
Node* topLeft;
Node* topRight;
Node* bottomLeft;
Node* bottomRight;
Node() {
val = false;
isLeaf = false;
topLeft = NULL;
topRight = NULL;
bottomLeft = NULL;
bottomRight = NULL;
}
Node(bool _val, bool _isLeaf) {
val = _val;
isLeaf = _isLeaf;
topLeft = NULL;
topRight = NULL;
bottomLeft = NULL;
bottomRight = NULL;
}
Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) {
val = _val;
isLeaf = _isLeaf;
topLeft = _topLeft;
topRight = _topRight;
bottomLeft = _bottomLeft;
bottomRight = _bottomRight;
}
};
*/
class Solution {
public:
Node* construct(vector<vector<int>>& grid) {
return helper(grid, 0, 0, grid.size());
}
private:
Node* helper(const vector<vector<int>>& grid, int i, int j, int w) {
if (allSame(grid, i, j, w))
return new Node(grid[i][j], true);
Node* node = new Node(true, false);
node->topLeft = helper(grid, i, j, w / 2);
node->topRight = helper(grid, i, j + w / 2, w / 2);
node->bottomLeft = helper(grid, i + w / 2, j, w / 2);
node->bottomRight = helper(grid, i + w / 2, j + w / 2, w / 2);
return node;
}
bool allSame(const vector<vector<int>>& grid, int i, int j, int w) {
return all_of(begin(grid) + i, begin(grid) + i + w,
[&](const vector<int>& row) {
return all_of(begin(row) + j, begin(row) + j + w,
[&](int num) { return num == grid[i][j]; });
});
}
};