427. Construct Quad Tree
- 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.