# 427. Construct Quad Tree

**<font color=red>难度: Easy</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/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 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.
```

## 解题方案

> 思路 1
******- 时间复杂度: O(row * col)******- 空间复杂度: O(row * col)******


递归，beats 33.45%

```python
class Solution:
    def construct(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: Node
        """
        def helper(r1, r2, c1, c2, grid):
            if r1 > r2 or c1 > c2:
                return
            is_leaf = all(grid[i][j] == grid[r1][c1] for i in range(r1, r2+1) for j in range(c1, c2+1))
            if is_leaf:
                return Node(grid[r1][c1] == 1, True, None, None, None, None)
            topLeft = helper(r1, (r1+r2)//2, c1, (c1+c2)//2, grid)
            topRight = helper(r1, (r1+r2)//2, (c1+c2)//2+1, c2, grid)
            bottomLeft = helper((r1+r2)//2+1, r2, c1, (c1+c2)//2, grid)
            bottomRight = helper((r1+r2)//2+1, r2, (c1+c2)//2+1, c2, grid)
            return Node(False, False, topLeft, topRight, bottomLeft, bottomRight)
        
        return helper(0, len(grid)-1, 0, len(grid[0])-1, grid)
```



























