forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogical-or-of-two-binary-grids-represented-as-quad-trees.cpp
48 lines (45 loc) · 1.59 KB
/
logical-or-of-two-binary-grids-represented-as-quad-trees.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
// 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* intersect(Node* quadTree1, Node* quadTree2) {
if (quadTree1->isLeaf) {
return quadTree1->val ? quadTree1 : quadTree2;
} else if (quadTree2->isLeaf) {
return quadTree2->val ? quadTree2 : quadTree1;
}
auto topLeftNode = intersect(quadTree1->topLeft, quadTree2->topLeft);
auto topRightNode = intersect(quadTree1->topRight, quadTree2->topRight);
auto bottomLeftNode = intersect(quadTree1->bottomLeft, quadTree2->bottomLeft);
auto bottomRightNode = intersect(quadTree1->bottomRight, quadTree2->bottomRight);
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);
}
};