|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# @Author: 何睿 |
| 3 | +# @Create Date: 2019-12-14 10:29:10 |
| 4 | +# @Last Modified by: 何睿 |
| 5 | +# @Last Modified time: 2019-12-14 10:39:51 |
| 6 | + |
| 7 | + |
| 8 | +class Node: |
| 9 | + def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight): |
| 10 | + self.val = val |
| 11 | + self.isLeaf = isLeaf |
| 12 | + self.topLeft = topLeft |
| 13 | + self.topRight = topRight |
| 14 | + self.bottomLeft = bottomLeft |
| 15 | + self.bottomRight = bottomRight |
| 16 | + |
| 17 | + |
| 18 | +class Solution: |
| 19 | + def construct(self, grid): |
| 20 | + return self.dfs(grid, 0, 0, len(grid)) |
| 21 | + |
| 22 | + def dfs(self, grid, h, w, N): |
| 23 | + |
| 24 | + total = sum([grid[h + i][w + j] for i in range(N) for j in range(N)]) # 求取当前方格内的和 |
| 25 | + |
| 26 | + if total == 0: # 如果方格内所有元素都是0 |
| 27 | + return Node(False, True, None, None, None, None) # 构造一个值为False的叶子节点 |
| 28 | + |
| 29 | + elif total == N * N: # 如果方格内所有元素都是1 |
| 30 | + return Node(True, True, None, None, None, None) # 构造一个值为True的叶子节点 |
| 31 | + |
| 32 | + else: # 说明方格内有0有1 |
| 33 | + root = Node('*', False, None, None, None, None) # 构造一个值为"*"的中间结点 |
| 34 | + n = N // 2 # 求方格的一半 |
| 35 | + root.topLeft = self.dfs(grid, h, w, n) # 构建左上子树 |
| 36 | + root.topRight = self.dfs(grid, h, w + n, n) # 构建右上子树 |
| 37 | + root.bottomLeft = self.dfs(grid, h + n, w, n) # 构建左下子树 |
| 38 | + root.bottomRight = self.dfs(grid, h + n, w + n, n) # 构建右下子树 |
| 39 | + return root |
0 commit comments