You are given a n * n binary matrix grid. We want to represent grid with a Quad-Tree.
Return the root of the Quad-Tree representing grid.
A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:
isLeaf: True if the node is a leaf node on the tree or False if the node has four children.val: True if the node represents a grid cell of1'sor False if the node represents a grid cell of0's. Notice that you can assign thevalto True or False whenisLeafis False, and both are accepted in the answer.
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 grid using the following steps:
If the current grid has the same value (i.e all
1'sor all0's), setisLeafTrue and setvalto the value of the grid and set the four children to Null and stop.If the current grid has different values, set
isLeafto False and setvalto any value and divide the current grid into four sub-grids representing the four childrens of the current node.Recurse the steps for every children of the current node.
Example 1:
Input: grid = [[1,1],[1,1]]
Output: [[1,1]]Example 2:
Input: grid = [
[1,1,1,1],
[0,0,0,0],
[1,1,1,1],
[1,1,1,1]
]
Output: [[0,0],[0,0],[0,0],[1,1],[1,1],[1,1],[1,1],[1,0],[1,0],[1,1],[1,1],[1,0],[1,0]]Constraints:
n == grid.length == grid[i].lengthn == (2^x)where0 <= x <= 6