Logical OR of Two Binary Grids Represented as Quad-Trees LeetCode solution in C++

1
class Solution {
2
public:
3
Node *intersect(Node *quadTree1, Node *quadTree2) {
4
if (quadTree1->isLeaf && quadTree2->isLeaf) {
5
return new Node(quadTree1->val || quadTree2->val, true);
6
}
7
if (quadTree1->isLeaf) {
8
if (quadTree1->val) return quadTree1;
9
return quadTree2;
10
}
11
if (quadTree2->isLeaf) {
12
if (quadTree2->val) return quadTree2;
13
return quadTree1;
14
}
15

16
Node *topLeft = intersect(quadTree1->topLeft, quadTree2->topLeft);
17
Node *topRight = intersect(quadTree1->topRight, quadTree2->topRight);
18
Node *bottomLeft = intersect(quadTree1->bottomLeft, quadTree2->bottomLeft);
19
Node *bottomRight = intersect(quadTree1->bottomRight, quadTree2->bottomRight);
20

21
Node *newnode = new Node();
22

23
if (topLeft->isLeaf && topRight->isLeaf && bottomLeft->isLeaf && bottomRight->isLeaf &&
24
topLeft->val == topRight->val && bottomLeft->val == bottomRight->val &&
25
topLeft->val == bottomRight->val) {
26
newnode->isLeaf = true;
27
newnode->val = topLeft->val;
28
} else {
29
newnode->topLeft = topLeft;
30
newnode->topRight = topRight;
31
newnode->bottomLeft = bottomLeft;
32
newnode->bottomRight = bottomRight;
33
}
34

35
return newnode;
36
}
37
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0