Leetcode 427. Construct Quad Tree
Given a n * n matrix grid of 0s and 1s 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 True, and assign the children for a False node in the following order:
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: a boolean value that is True if the node is a leaf node and False if it is an internal node.We can construct a Quad-Tree from a two-dimensional area using the following steps:
1s or all 0s), set isLeaf to True and set val to the value of the grid, and set the four children to Null.isLeaf to False and set val to any value, and divide the current grid into four sub-grids as shown in the problem description.n?n always a power of 2?Assumption: n is always a power of 2, making it easier to recursively divide the grid evenly.
Node to store val, isLeaf, and the four children (topLeft, topRight, bottomLeft, bottomRight).class Node {
public boolean val;
public boolean isLeaf;
public Node topLeft;
public Node topRight;
public Node bottomLeft;
public Node bottomRight;
public Node() {}
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;
}
}
public class Solution {
public Node construct(int[][] grid) {
return construct(grid, 0, 0, grid.length);
}
private Node construct(int[][] grid, int row, int col, int length) {
if (isUniform(grid, row, col, length)) {
return new Node(grid[row][col] == 1, true);
}
int halfLength = length / 2;
Node topLeft = construct(grid, row, col, halfLength);
Node topRight = construct(grid, row, col + halfLength, halfLength);
Node bottomLeft = construct(grid, row + halfLength, col, halfLength);
Node bottomRight = construct(grid, row + halfLength, col + halfLength, halfLength);
return new Node(
false,
false,
topLeft,
topRight,
bottomLeft,
bottomRight
);
}
private boolean isUniform(int[][] grid, int row, int col, int length) {
int value = grid[row][col];
for (int i = row; i < row + length; i++) {
for (int j = col; j < col + length; j++) {
if (grid[i][j] != value) {
return false;
}
}
}
return true;
}
}
O(n^2 log n) where n is the width/height of the grid.
isUniform check is O(n^2) for each level.log n.O(log n) due to the recursion stack.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?