题目如下:
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
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 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.
解题思路:递归,不是叶子节点就继续拆分成上下左右四个子节点。
代码如下:
""" # Definition for a QuadTree node. class Node(object): def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight): self.val = val self.isLeaf = isLeaf self.topLeft = topLeft self.topRight = topRight self.bottomLeft = bottomLeft self.bottomRight = bottomRight """ class Solution(object): def construct(self, grid): """ :type grid: List[List[int]] :rtype: Node """ def check(tl_x,tl_y,br_x,br_y): count = 0 for i in range(tl_x,br_x): for j in range(tl_y,br_y): count += grid[i][j] if count == 0: return 0 elif count == (br_x - tl_x) * (br_y - tl_y): return 1 return -1 def connect(parent,child,direction): if direction == 'TL': parent.topLeft = child if direction == 'TR': parent.topRight = child if direction == 'BL': parent.bottomLeft = child if direction == 'BR': parent.bottomRight = child def recursive(tl_x,tl_y,br_x,br_y,parent,direction): if check(tl_x,tl_y,br_x,br_y) == 0: node = Node(0,True,None,None,None,None) if self.root == None: self.root = node else: connect(parent,node,direction) elif check(tl_x,tl_y,br_x,br_y) == 1: node = Node(1,True,None,None,None,None) if self.root == None: self.root = node else: connect(parent,node,direction) else: node = Node('*',False,None,None,None,None) mid_x = (br_x + tl_x)/2 mid_y = (br_y + tl_y)/2 if self.root == None: self.root = node else: connect(parent,node,direction) recursive(tl_x,tl_y,mid_x,mid_y,node,'TL') recursive(tl_x, mid_y, mid_x, br_y, node, 'TR') recursive(mid_x, tl_y, br_x, mid_y , node, 'BL') recursive(mid_x, mid_y, br_x, br_y, node, 'BR') self.root = None recursive(0,0,len(grid),len(grid[0]),None,'') return self.root