题目描述:
We want to use quad trees to store an N x N boolean grid. Each cell in the grid can only be true or false. The root node represents the whole grid. For each node, it will be subdivided into four children nodes until the values in the region it represents are all the same.
Each node has another two boolean attributes : isLeaf and val. isLeaf is true if and only if the node is a leaf node. The valattribute for a leaf node contains the value of the region it represents.
Your task is to use a quad tree to represent a given grid. The following example may help you understand the problem better:
The corresponding quad tree should be as following, where each node is represented as a (isLeaf, val) pair.
Note:
1. N is less than 1000 and guaranteened to be a power of 2.
2. If you want to know more about the quad tree, you can refer to its wiki.
/*
// 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) {
if(grid.size()==0) return NULL;
return helper(grid,0,0,grid.size());
}
Node* helper(vector<vector<int>>& grid, int x, int y, int n)
{
for(int i=x;i<x+n;i++)
{
for(int j=y;j<y+n;j++)
{
if(grid[i][j]!=grid[x][y])
{ //发现正方形区域内的值存在不同,说明不是叶节点,调用递归得到子节点
Node* root=new Node(true,false,NULL,NULL,NULL,NULL);
root->topLeft=helper(grid,x,y,n/2);
root->topRight=helper(grid,x,y+n/2,n/2);
root->bottomLeft=helper(grid,x+n/2,y,n/2);
root->bottomRight=helper(grid,x+n/2,y+n/2,n/2);
return root;
}
}
}
bool val=grid[x][y];
return new Node(val,true,NULL,NULL,NULL,NULL);
}
};