forked from VivekDubey9/Competitive-Programming-Algos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
construct-quad-tree.cpp
54 lines (52 loc) · 1.64 KB
/
construct-quad-tree.cpp
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
// Time: O(n)
// Space: O(h)
/*
// Definition for a QuadTree node.
class Node {
public:
bool val;
bool isLeaf;
Node* topLeft;
Node* topRight;
Node* bottomLeft;
Node* bottomRight;
Node() {}
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) {
if (grid.empty()) {
return nullptr;
}
return dfs(grid, 0, 0, grid.size());
}
private:
Node* dfs(const vector<vector<int>>& grid,
int x, int y, int l) {
if (l == 1) {
return new Node(grid[x][y] == 1, true, nullptr, nullptr, nullptr, nullptr);
}
int half = l / 2;
auto topLeftNode = dfs(grid, x, y, half);
auto topRightNode = dfs(grid, x, y + half, half);
auto bottomLeftNode = dfs(grid, x + half, y, half);
auto bottomRightNode = dfs(grid, x + half, y + half, half);
if (topLeftNode->isLeaf && topRightNode->isLeaf &&
bottomLeftNode->isLeaf && bottomRightNode->isLeaf &&
topLeftNode->val == topRightNode->val &&
topRightNode->val == bottomLeftNode->val &&
bottomLeftNode->val == bottomRightNode->val) {
return new Node(topLeftNode->val, true, nullptr, nullptr, nullptr, nullptr);
}
return new Node(true, false, topLeftNode, topRightNode, bottomLeftNode, bottomRightNode);
}
};