427 Construct Quad Tree 建立四叉樹
Description:
Given a n * n matrix grid of 0's and 1's only. We want to represent the grid with a Quad-Tree.
Return the root of the Quad-Tree representing the grid.
Notice that you can assign the value of a node to True or False when isLeaf is False, and both are accepted in the answer.
A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:
val: True if the node represents a grid of 1's or False if the node represents a grid of 0's.
isLeaf: True if the node is leaf node on the tree or False if the node has the four children.
class Node {
public boolean val;
public boolean isLeaf;
public Node topLeft;
public Node topRight;
public Node bottomLeft;
public Node bottomRight;
}
We can construct a Quad-Tree from a two-dimensional area using the following steps:
If the current grid has the same value (i.e all 1's or all 0's) set isLeaf True and set val to the value of the grid and set the four children to Null and stop.
If the current grid has different values, set isLeaf to False and set val to any value and divide the current grid into four sub-grids as shown in the photo.
Recurse for each of the children with the proper sub-grid.
If you want to know more about the Quad-Tree, you can refer to the wiki.
Quad-Tree format:
The output represents the serialized format of a Quad-Tree using level order traversal, where null signifies a path terminator where no node exists below.
It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val].
If the value of isLeaf or val is True we represent it as 1 in the list [isLeaf, val] and if the value of isLeaf or val is False we represent it as 0.
Example:
Example 1:
Input: grid = [[0,1],[1,0]]
Output: [[0,1],[1,0],[1,1],[1,1],[1,0]]
Explanation: The explanation of this example is shown below:
Notice that 0 represnts False and 1 represents True in the photo representing the Quad-Tree.
Example 2:
Input: grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]]
Output: [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]
Explanation: All values in the grid are not the same. We divide the grid into four sub-grids.
The topLeft, bottomLeft and bottomRight each has the same value.
The topRight have different values so we divide it into 4 sub-grids where each has the same value.
Explanation is shown in the photo below:
Example 3:
Input: grid = [[1,1],[1,1]]
Output: [[1,1]]
Example 4:
Input: grid = [[0]]
Output: [[1,0]]
Example 5:
Input: grid = [[1,1,0,0],[1,1,0,0],[0,0,1,1],[0,0,1,1]]
Output: [[0,1],[1,1],[1,0],[1,0],[1,1]]
Constraints:
n == grid.length == grid[i].length
n == 2^x where 0 <= x <= 6
題目描述:
給你一個 n * n 矩陣 grid ,矩陣由若干 0 和 1 組成。請你用四叉樹表示該矩陣 grid 拴竹。
你需要返回能表示矩陣的 四叉樹 的根結(jié)點。
注意魁兼,當(dāng) isLeaf 為 False 時具篇,你可以把 True 或者 False 賦值給節(jié)點盯腌,兩種值都會被判題機(jī)制 接受 沃斤。
四叉樹數(shù)據(jù)結(jié)構(gòu)中,每個內(nèi)部節(jié)點只有四個子節(jié)點访敌。此外凉敲,每個節(jié)點都有兩個屬性:
val:儲存葉子結(jié)點所代表的區(qū)域的值。1 對應(yīng) True寺旺,0 對應(yīng) False爷抓;
isLeaf: 當(dāng)這個節(jié)點是一個葉子結(jié)點時為 True,如果它有 4 個子節(jié)點則為 False 阻塑。
class Node {
public boolean val;
public boolean isLeaf;
public Node topLeft;
public Node topRight;
public Node bottomLeft;
public Node bottomRight;
}
我們可以按以下步驟為二維區(qū)域構(gòu)建四叉樹:
如果當(dāng)前網(wǎng)格的值相同(即蓝撇,全為 0 或者全為 1),將 isLeaf 設(shè)為 True 陈莽,將 val 設(shè)為網(wǎng)格相應(yīng)的值渤昌,并將四個子節(jié)點都設(shè)為 Null 然后停止。
如果當(dāng)前網(wǎng)格的值不同走搁,將 isLeaf 設(shè)為 False独柑, 將 val 設(shè)為任意值,然后如下圖所示私植,將當(dāng)前網(wǎng)格劃分為四個子網(wǎng)格忌栅。
使用適當(dāng)?shù)淖泳W(wǎng)格遞歸每個子節(jié)點。
如果你想了解更多關(guān)于四叉樹的內(nèi)容曲稼,可以參考 wiki 索绪。
四叉樹格式:
輸出為使用層序遍歷后四叉樹的序列化形式,其中 null 表示路徑終止符贫悄,其下面不存在節(jié)點瑞驱。
它與二叉樹的序列化非常相似。唯一的區(qū)別是節(jié)點以列表形式表示 [isLeaf, val] 窄坦。
如果 isLeaf 或者 val 的值為 True 唤反,則表示它在列表 [isLeaf, val] 中的值為 1 ;如果 isLeaf 或者 val 的值為 False 鸭津,則表示值為 0 彤侍。
示例 :
示例 1:
輸入:grid = [[0,1],[1,0]]
輸出:[[0,1],[1,0],[1,1],[1,1],[1,0]]
解釋:此示例的解釋如下:
請注意,在下面四叉樹的圖示中曙博,0 表示 false拥刻,1 表示 True 怜瞒。
示例 2:
輸入:grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]]
輸出:[[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]
解釋:網(wǎng)格中的所有值都不相同父泳。我們將網(wǎng)格劃分為四個子網(wǎng)格般哼。
topLeft,bottomLeft 和 bottomRight 均具有相同的值惠窄。
topRight 具有不同的值蒸眠,因此我們將其再分為 4 個子網(wǎng)格,這樣每個子網(wǎng)格都具有相同的值杆融。
解釋如下圖所示:
示例 3:
輸入:grid = [[1,1],[1,1]]
輸出:[[1,1]]
示例 4:
輸入:grid = [[0]]
輸出:[[1,0]]
示例 5:
輸入:grid = [[1,1,0,0],[1,1,0,0],[0,0,1,1],[0,0,1,1]]
輸出:[[0,1],[1,1],[1,0],[1,0],[1,1]]
提示:
n == grid.length == grid[i].length
n == 2^x 其中 0 <= x <= 6
思路:
按照左上, 右上, 左下和右下分為 4個區(qū)域
檢查區(qū)域是否一致, 不一致則不是葉子節(jié)點
一致則生成葉子節(jié)點
將區(qū)域減小到 1 / 2(面積為原來的 1 / 4), 遞歸檢查
時間復(fù)雜度O(n ^ 2lgn), 空間復(fù)雜度O(1)
代碼:
C++:
/*
// Definition for a QuadTree node.
class Node {
public:
bool val;
bool isLeaf;
Node* topLeft;
Node* topRight;
Node* bottomLeft;
Node* bottomRight;
Node() {
val = false;
isLeaf = false;
topLeft = NULL;
topRight = NULL;
bottomLeft = NULL;
bottomRight = NULL;
}
Node(bool _val, bool _isLeaf) {
val = _val;
isLeaf = _isLeaf;
topLeft = NULL;
topRight = NULL;
bottomLeft = NULL;
bottomRight = NULL;
}
Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) {
val = _val;
isLeaf = _isLeaf;
topLeft = _topLeft;
topRight = _topRight;
bottomLeft = _bottomLeft;
bottomRight = _bottomRight;
}
};
*/
class Solution
{
public:
Node* construct(vector<vector<int>>& grid)
{
return quad_tree(grid, 0, 0, grid.size());
}
private:
Node* quad_tree(vector<vector<int>>& grid, int x, int y, int offset)
{
for (int i = x; i < x + offset; i++) for (int j = y; j < y + offset; j++) if (grid[i][j] != grid[x][y]) return new Node(true, false, quad_tree(grid, x, y, offset >> 1), quad_tree(grid, x, y + (offset >> 1), offset >> 1), quad_tree(grid, x + (offset >> 1), y, offset >> 1), quad_tree(grid, x + (offset >> 1), y + (offset >> 1), offset >> 1));
return new Node(grid[x][y], true);
}
};
Java:
/*
// Definition for a QuadTree node.
class Node {
public boolean val;
public boolean isLeaf;
public Node topLeft;
public Node topRight;
public Node bottomLeft;
public Node bottomRight;
public Node() {
this.val = false;
this.isLeaf = false;
this.topLeft = null;
this.topRight = null;
this.bottomLeft = null;
this.bottomRight = null;
}
public Node(boolean val, boolean isLeaf) {
this.val = val;
this.isLeaf = isLeaf;
this.topLeft = null;
this.topRight = null;
this.bottomLeft = null;
this.bottomRight = null;
}
public Node(boolean val, boolean isLeaf, Node topLeft, Node topRight, Node bottomLeft, Node bottomRight) {
this.val = val;
this.isLeaf = isLeaf;
this.topLeft = topLeft;
this.topRight = topRight;
this.bottomLeft = bottomLeft;
this.bottomRight = bottomRight;
}
};
*/
class Solution {
public Node construct(int[][] grid) {
return quadTree(grid, 0, 0, grid.length);
}
private Node quadTree(int[][] grid, int x, int y, int offset) {
for (int i = x; i < x + offset; i++) for (int j = y; j < y + offset; j++) if (grid[x][y] != grid[i][j]) return new Node(true, false, quadTree(grid, x, y, offset >> 1), quadTree(grid, x, y + (offset >> 1), offset >> 1), quadTree(grid, x + (offset >> 1), y, offset >> 1), quadTree(grid, x + (offset >> 1), y + (offset >> 1), offset >> 1));
return new Node(grid[x][y] == 1, true);
}
}
Python:
"""
# 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: List[List[int]]) -> 'Node':
return Node(bool(s), True) if not (s := sum(map(sum, grid))) or not (m := len(grid) >> 1) or s == 4 * m * m else Node(True, False, self.construct([g[:m] for g in grid[:m]]), self.construct([g[m:] for g in grid[:m]]), self.construct([g[:m] for g in grid[m:]]), self.construct([g[m:] for g in grid[m:]]))