1
+ /*
2
+ // Definition for a QuadTree node.
3
+ class Node {
4
+ public:
5
+ bool val;
6
+ bool isLeaf;
7
+ Node* topLeft;
8
+ Node* topRight;
9
+ Node* bottomLeft;
10
+ Node* bottomRight;
11
+
12
+ Node() {}
13
+
14
+ Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) {
15
+ val = _val;
16
+ isLeaf = _isLeaf;
17
+ topLeft = _topLeft;
18
+ topRight = _topRight;
19
+ bottomLeft = _bottomLeft;
20
+ bottomRight = _bottomRight;
21
+ }
22
+ };
23
+ */
24
+ class Solution {
25
+ public:
26
+ Node* construct (vector<vector<int >>& grid) {
27
+ return build (grid, 0 , grid.size (), 0 , grid.size ()) ;
28
+ }
29
+ Node *build (vector<vector<int >> &g, int l, int r, int t, int b)
30
+ {
31
+ Node *node = new Node ;
32
+ node->topLeft = NULL ;
33
+ node->topRight = NULL ;
34
+ node->bottomLeft = NULL ;
35
+ node->bottomRight = NULL ;
36
+ node->isLeaf = false ;
37
+
38
+ bool tl, tr, bl, br ;
39
+ if (l + 1 == r)
40
+ {
41
+ node->val = g[t][l] ;
42
+ node->isLeaf = true ;
43
+ return node ;
44
+ }
45
+
46
+ int vmid = (l+r)>>1 ;
47
+ int hmid = (t+b)>>1 ;
48
+ node->topLeft = build (g, l, vmid, t, hmid) ;
49
+ node->topRight = build (g, vmid, r, t, hmid) ;
50
+ node->bottomLeft = build (g, l, vmid, hmid, b) ;
51
+ node->bottomRight = build (g, vmid, r, hmid, b) ;
52
+
53
+ if (node->topLeft ->isLeaf && node->topRight ->isLeaf && node->bottomLeft ->isLeaf && node->bottomRight ->isLeaf )
54
+ {
55
+ if (node->topLeft ->val && node->topRight ->val && node->bottomLeft ->val && node->bottomRight ->val
56
+ || !(node->topLeft ->val || node->topRight ->val || node->bottomLeft ->val || node->bottomRight ->val ))
57
+ {
58
+ node->val = node->topLeft ->val ;
59
+ node->isLeaf = true ;
60
+
61
+ delete (node->topLeft ) ;
62
+ delete (node->topRight ) ;
63
+ delete (node->bottomLeft ) ;
64
+ delete (node->bottomRight ) ;
65
+
66
+ node->topLeft = NULL ;
67
+ node->topRight = NULL ;
68
+ node->bottomLeft = NULL ;
69
+ node->bottomRight = NULL ;
70
+ }
71
+ }
72
+ return node ;
73
+ }
74
+ };
0 commit comments