We want to use quad trees to store an `N x N` boolean grid. Each cell in the grid can only be true or false. The root node represents the whole grid. For each node, it will be subdivided into four children nodes until the values in the region it represents are all the same.

Each node has another two boolean attributes : `isLeaf` and `val``isLeaf` is true if and only if the node is a leaf node. The `val` attribute for a leaf node contains the value of the region it represents.

Given the `8 x 8` grid below, we want to construct the corresponding quad tree:

It can be divided according to the definition above:

The corresponding quad tree should be as following, where each node is represented as a `(isLeaf, val)`pair.

For the non-leaf nodes, `val` can be arbitrary, so it is represented as `*`.

Note:

1. `N` is less than `1000` and guaranteened to be a power of 2.
2. If you want to know more about the quad tree, you can refer to its wiki.

``````class Solution {
public:
Node* construct(vector<vector<int>>& grid) {
return build(grid, 0, 0, grid.size());
}
Node* build(vector<vector<int>>& grid, int x, int y, int len) {
if (len <= 0) return NULL;
for (int i = x; i < x + len; ++i) {
for (int j = y; j < y + len; ++j) {
if (grid[i][j] != grid[x][y]) {
return new Node(true, false,
build(grid, x, y, len / 2),
build(grid, x, y + len / 2, len / 2),
build(grid, x + len/ 2, y, len / 2),
build(grid, x + len / 2, y + len / 2, len / 2));
}
}
}
return new Node(grid[x][y] == 1, true, NULL, NULL, NULL, NULL);
}
};
``````

``````class Solution {
public:
Node* construct(vector<vector<int>>& grid) {
return build(grid, 0, 0, grid.size() - 1, grid.size() - 1);
}
Node* build(vector<vector<int>>& grid, int r1, int c1, int r2, int c2) {
if (r1 > r2 || c1 > c2) return NULL;
bool isLeaf = true;
int val = grid[r1][c1], rowMid = (r1 + r2) / 2, colMid = (c1 + c2) / 2;
for (int i = r1; i <= r2; ++i) {
for (int j = c1; j <= c2; ++j) {
if (grid[i][j] != val) {
isLeaf = false;
break;
}
}
}
if (isLeaf) return new Node(val == 1, true, NULL, NULL, NULL, NULL);
return new Node(false, false,
build(grid, r1, c1, rowMid, colMid),
build(grid, r1, colMid + 1, rowMid, c2),
build(grid, rowMid + 1, c1, r2, colMid),
build(grid, rowMid + 1, colMid + 1, r2, c2));
}
};
``````