# LeetCode 427. Construct Quad Tree

## Description

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.

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 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.

## 描述

N 将小于 1000 且确保是 2 的整次幂。

### 思路

```# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-12-14 10:29:10

class Node:
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:
def construct(self, grid):
return self.dfs(grid, 0, 0, len(grid))

def dfs(self, grid, h, w, N):

# 求取当前方格内的和
total = sum([grid[h + i][w + j] for i in range(N) for j in range(N)])

# 如果方格内所有元素都是0,构造 False 节点
if total == 0:
return Node(False, True, None, None, None, None)
# 如果全部为 1，构造 True节点
elif total == N * N:
return Node(True, True, None, None, None, None)
# 否则拆分方格子，分别构造
else:
root = Node('*', False, None, None, None, None)
n = N // 2
root.topLeft = self.dfs(grid, h, w, n)
root.topRight = self.dfs(grid, h, w + n, n)
root.bottomLeft = self.dfs(grid, h + n, w, n)
root.bottomRight = self.dfs(grid, h + n, w + n, n)
return root

```

Posted in LeetCode and tagged .

### 何 睿

This site uses Akismet to reduce spam. Learn how your comment data is processed.