letecode [427] - Construct Quad Tree
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 val
attribute 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:
Given the 8 x 8
grid below, we want to construct the corresponding quad tree:
It can be divided according to the definition above:
The corresponding quad tree should be as following, where each node is represented as a (isLeaf, val)
pair.
For the non-leaf nodes, val
can be arbitrary, so it is represented as *
.
Note:
N
is less than1000
and guaranteened to be a power of 2.- If you want to know more about the quad tree, you can refer to its wiki.
题目大意:
用四叉树表示NxN的布尔型网格。网络中每一格的值只会是真或假。树的根结点代表整个网络。对于每个结点, 它将被分等成四个孩子结点直到这个区域内的值都是相同的.
每个结点还有另外两个布尔变量: isLeaf 和 val。isLeaf 当这个节点是一个叶子结点时为真。val 变量储存叶子结点所代表的区域的值。
理 解:
看的别人的解法。最开始没有明白题目的意思。题目是说若存在当前区域(初始为NxN网格)存在不同值元素,即将当前网格划分为四个小网格,当前网格表示为父节点,四个小网格表示为子节点;
直到当前区域的所有值元素相同,则当前区域作为叶子节点。
则每次划分网格时,只用记录网格的起始位置和长度,遇到不同元素即分割当前区域:起始位置改变、长度减半,否则,当前区域为叶子节点。
代 码 C++:
/* // 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* newNode(vector<vector<int>>& grid,int x,int y,int len){ if(len<=0) return NULL; for(int i=x;i<x+len;++i){ for(int j=y;j<y+len;++j){ if(grid[i][j]!=grid[x][y]){ return new Node(true,false,newNode(grid,x,y,len/2),newNode(grid,x,y+len/2,len/2),newNode(grid,x+len/2,y,len/2),newNode(grid,x+len/2,y+len/2,len/2)); } } } return new Node(grid[x][y]==1,true,NULL,NULL,NULL,NULL); } Node* construct(vector<vector<int>>& grid) { return newNode(grid,0,0,grid.size()); } };
运行结果:
执行用时 :308 ms, 在所有 C++ 提交中击败了45.91%的用户