我们想要使用一棵四叉树来储存一个 N x N 的布尔值网络。网络中每一格的值只会是真或假。树的根结点代表整个网络。对于每个结点, 它将被分等成四个孩子结点直到这个区域内的值都是相同的.
对应的四叉树应该像下面这样,每个结点由一对 (isLeaf, val) 所代表.
递归建立,判断和来确定是否全0或全1.
/*
// 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) {
int N=grid.size();
if(N==0) return NULL;
int sum =0;
for(auto r:grid)
for(auto c: r)
sum +=c;
// cout<<sum<<endl;
if( sum== N*N || sum ==0)
{
return new Node(grid[0][0],true, NULL,NULL,NULL,NULL);
}
vector<vector<int>> tl(N/2,vector<int>(N/2,0));
vector<vector<int>> tr(N/2,vector<int>(N/2,0));
vector<vector<int>> bl(N/2,vector<int>(N/2,0));
vector<vector<int>> br(N/2,vector<int>(N/2,0));
bool ftl, ftr,fbl, fbr;
for(int i=0;i<N/2;i++)
for(int j=0;j<N/2;j++)
{
tl[i][j]=grid[i][j];
bl[i][j]=grid[i+N/2][j];
tr[i][j]=grid[i][j+N/2];
br[i][j]=grid[i+N/2][j+N/2];
}
return new Node(false,false,construct(tl),construct(tr),construct(bl),construct(br));
}
};