LeetCode 427. Construct Quad Tree解题报告(python)

427. Construct Quad Tree

  1. Construct Quad Tree python solution

题目描述

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:
在这里插入图片描述
在这里插入图片描述

解析

还是要采用递归的思想解题。但只这里有两个属性。第一个属性是isLeaf如果是叶子节点,那么就是true。另一个属性是val,只有数值为1时才为True.

class Solution:
    def construct(self, grid):

        def helper(grid, row, col, length):
            if length == 1:
                return Node(grid[row][col] == 1, True, None, None, None, None)

            topLeft = helper(grid, row, col, length // 2)
            topRight = helper(grid, row, col + length // 2, length // 2)
            bottomLeft = helper(grid, row + length // 2, col, length // 2)
            bottomRight = helper(grid, row + length // 2, col + length // 2, length // 2)

            if topLeft.isLeaf == topRight.isLeaf == bottomLeft.isLeaf == bottomRight.isLeaf == True:
                if topLeft.val == topRight.val == bottomLeft.val == bottomRight.val:
                    return Node(topLeft.val, True, None, None, None, None)

            return Node("*", False, topLeft, topRight, bottomLeft, bottomRight)

        return helper(grid, 0, 0, len(grid))

Reference

https://leetcode.com/problems/construct-quad-tree/discuss/404425/Python-solution-with-explanation.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值