Construct Quad Tree
Last updated
Last updated
quad trees
, data structure
We want to use quad trees to store anN 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
andval
.isLeaf
is true if and only if the node is a leaf node. Theval
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 the8 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 than 1000
and guaranteened to be a power of 2.
If you want to know more about the quad tree, you can refer to its wiki.
难在对于题意的理解:
判断isLeaf:这里用每个square的左上角作为val,循环该square内所有元素,如果有不同元素,说明还需要继续拆分square,也就是isLeaf = false;否则如果全部元素都是相同的,说明isLeaf = true
recursively build:在于如果isLeaf = false时,如何对sqaure进行分割,这里可以借鉴binary search的计算,寻找每个square的区间中值,作为细分square的坐标。