題目:
我們想要使用一棵四叉樹來儲存一個 N x N
的布爾值網絡。網絡中每一格的值只會是真或假。樹的根結點代表整個網絡。對於每個結點, 它將被分等成四個孩子結點直到這個區域內的值都是相同的.
每個結點還有另外兩個布爾變量: isLeaf
和 val
。isLeaf
當這個節點是一個葉子結點時爲真。val
變量儲存葉子結點所代表的區域的值。
你的任務是使用一個四叉樹表示給定的網絡。下面的例子將有助於你理解這個問題:
給定下面這個8 x 8
網絡,我們將這樣建立一個對應的四叉樹:
由上文的定義,它能被這樣分割:
對應的四叉樹應該像下面這樣,每個結點由一對 (isLeaf, val)
所代表.
對於非葉子結點,val
可以是任意的,所以使用 *
代替。
提示:
N
將小於1000
且確保是 2 的整次冪。- 如果你想了解更多關於四叉樹的知識,你可以參考這個 wiki 頁面。
python代碼:
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):
def dfs(x, y, l):
if l == 1:
node = Node(grid[x][y] == 1, True, None, None, None, None)
else:
tLeft = dfs(x, y, l // 2)
tRight = dfs(x, y + l // 2, l // 2)
bLeft = dfs(x + l // 2, y, l// 2)
bRight = dfs(x + l // 2, y + l // 2, l // 2)
value = tLeft.val or tRight.val or bLeft.val or bRight.val
if tLeft.isLeaf and tRight.isLeaf and bLeft.isLeaf and bRight.isLeaf and tLeft.val == tRight.val == bLeft.val == bRight.val:
node = Node(value, True, None, None, None, None)
else:
node = Node(value, False, tLeft, tRight, bLeft, bRight)
return node
return grid and dfs(0, 0, len(grid)) or None