题目地址:https://leetcode.com/problems/construct-quad-tree/description/

题目描述

Wewant 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:

 

Itcan be divided according to the definition above:

 

Thecorresponding quad tree should be as following, where each node is represented as a (isLeaf, val) pair.

Forthe non-leaf nodes, val can be arbitrary, so it is represented as *.

 

Note:

1、 Nislessthan1000andguaranteenedtobeapowerof2.;
2、 Ifyouwanttoknowmoreaboutthequadtree,youcanrefertoitswiki.;

题目大意

题目很长,但是不要害怕。

题目所说的四分树,其实就是用来表示矩阵数据的一种数据结构。

把一个边长为 2 的幂的正方形均分成 4 块,然后再均分到不能均分为止即为叶子节点。

树的节点分成两种:一种是叶子节点(矩阵内所有的取值一样),一种不是叶子节点(矩阵内的取值不一样,需要继续细分)。

具体地建立四叉树的过程,可以参考我画的图进行理解:      

解题方法

首先,这种结构就是「树」,肯定使用递归求解。重要的是如何判断此树结构如何判断叶子节点、val

所以定义了一个新的函数isQuadTree

  • 如果一个正方形中所有的数字都是 1,则 val 是 True;
  • 如果一个正方形中所有的数字都是 0,则 val 是 False。
  • 否则,说明格子里的值不都是相同的,返回 None.

判断leaf 的方法是看看格子里的所有的值是不是相同的,如果全是 1 或者 0 那么就是 leaf,否则就不是 leaf

其他的难点就在把正方形进行切分成四块了,这个不是难点。我用的是蠢方法,使用额外空间,把 4 个小区域都复制了一份出来。

"""
# Definition for a QuadTree node.
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):
        """
        :type grid: List[List[int]]
        :rtype: Node
        """
        isLeaf = self.isQuadTree(grid)
        _len = len(grid)
        if isLeaf == None:
            mid = _len // 2
            topLeftGrid = [[grid[i][j] for j in range(mid)] for i in range(mid)]
            topRightGrid = [[grid[i][j] for j in range(mid, _len)] for i in range(mid)]
            bottomLeftGrid = [[grid[i][j] for j in range(mid)] for i in range(mid, _len)]
            bottomRightGrid = [[grid[i][j] for j in range(mid, _len)] for i in range(mid, _len)]
            node = Node(True, False, self.construct(topLeftGrid), self.construct(topRightGrid), 
                        self.construct(bottomLeftGrid), self.construct(bottomRightGrid))
        elif isLeaf == False:
            node = Node(False, True, None, None, None, None)
        else:
            node = Node(True, True, None, None, None, None)
        return node
        
    def isQuadTree(self, grid):
        _len = len(grid)
        _sum = 0
        for i in range(_len):
            _sum += sum(grid[i])
        if _sum == _len ** 2:
            return True
        elif _sum == 0:
            return False
        else:
            return None

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

二刷,换了一种写法,也是递归。

"""
# 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
        """
        N = len(grid)
        if N == 1:
            return Node(grid[0][0] == 1, True, None, None, None, None)
        topLeftSum = sum([grid[i][j] for i in range(N/2) for j in range(N/2)])
        topRightSum = sum([grid[i][j] for i in range(N/2) for j in range(N/2, N)])
        bottomLeftSum = sum([grid[i][j] for i in range(N/2, N) for j in range(N/2)])
        bottomRightSum = sum(grid[i][j] for i in range(N/2, N) for j in range(N/2, N))
        node = Node(False, False, None, None, None, None)
        if topLeftSum == topRightSum == bottomLeftSum == bottomRightSum:
            if topLeftSum == 0:
                node.isLeaf = True
                node.val = False
            elif topLeftSum == (N / 2) ** 2:
                node.isLeaf = True
                node.val = True
        if node.isLeaf:
            return node
        node.val = True
        node.topLeft = self.construct([[grid[i][j] for j in range(N/2)] for i in range(N/2)])
        node.topRight = self.construct([[grid[i][j] for j in range(N/2, N)] for i in range(N/2)])
        node.bottomLeft = self.construct([[grid[i][j] for j in range(N/2)] for i in range(N/2, N)])
        node.bottomRight = self.construct([[grid[i][j] for j in range(N/2, N)] for i in range(N/2, N)])
        return node

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

DDKK.COM 弟弟快看-教程,程序员编程资料站,版权归原作者所有

本文经作者:负雪明烛 授权发布,任何组织或个人未经作者授权不得转发