Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3300192

Browse files
Create Construct Quad Tree
1 parent cafea12 commit 3300192

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

‎Top Interview 150/Construct Quad Tree

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
想法:Divide and Conquer 的問題,我們可以先用每個 size 為 1 的格子作為葉節點;接著往上回傳時,
2+
如果上層節點的所有子節點都是葉節點且數值皆相同的話,我們就 free 掉原本記憶體並新增一個合併後的葉節點即可
3+
4+
Time Complexity : O(n^2) for T(n) = 4 * T(n / 2) + O(1) , by Master Theorem , T(n) = O(n^(log_2(4))) = O(n^2)
5+
(or you can see that every grids only been visited one times)
6+
Space Complexity : O(n^2) for the tree (recursion depth = O(logn))
7+
8+
/*
9+
// Definition for a QuadTree node.
10+
class Node {
11+
public:
12+
bool val;
13+
bool isLeaf;
14+
Node* topLeft;
15+
Node* topRight;
16+
Node* bottomLeft;
17+
Node* bottomRight;
18+
19+
Node() {
20+
val = false;
21+
isLeaf = false;
22+
topLeft = NULL;
23+
topRight = NULL;
24+
bottomLeft = NULL;
25+
bottomRight = NULL;
26+
}
27+
28+
Node(bool _val, bool _isLeaf) {
29+
val = _val;
30+
isLeaf = _isLeaf;
31+
topLeft = NULL;
32+
topRight = NULL;
33+
bottomLeft = NULL;
34+
bottomRight = NULL;
35+
}
36+
37+
Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) {
38+
val = _val;
39+
isLeaf = _isLeaf;
40+
topLeft = _topLeft;
41+
topRight = _topRight;
42+
bottomLeft = _bottomLeft;
43+
bottomRight = _bottomRight;
44+
}
45+
};
46+
*/
47+
48+
class Solution {
49+
public:
50+
Node* constructnode(vector<vector<int>>& grid,int size , int top , int left){
51+
if (size == 1)
52+
return new Node( grid[top][left] ,true) ;
53+
54+
Node* topleft = constructnode(grid , size / 2 , top , left) ;
55+
Node* topright = constructnode(grid , size / 2 , top , left + size/2) ;
56+
Node* bottomleft = constructnode(grid , size / 2 , top + size/2 , left);
57+
Node* bottomright = constructnode(grid , size/2, top+size/2,left + size/2);
58+
59+
if (topleft->isLeaf && topright->isLeaf &&
60+
bottomleft->isLeaf && bottomright->isLeaf &&
61+
topleft->val == topright->val &&
62+
topleft->val == bottomleft->val &&
63+
topleft->val == bottomright->val) {
64+
delete(topleft) ;
65+
delete(topright) ;
66+
delete(bottomright) ;
67+
delete(bottomleft) ;
68+
return new Node(grid[top][left] , true) ;
69+
}
70+
return new Node(true , false , topleft,topright,bottomleft,bottomright) ;
71+
}
72+
Node* construct(vector<vector<int>>& grid) {
73+
return constructnode(grid , grid.size() , 0 , 0) ;
74+
}
75+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /