3
bool areValuesSame(vector<vector<int>> &grid, int rowStart, int rowEnd, int colStart,5
int val = grid[rowStart][colStart];6
for (int i = rowStart; i <= rowEnd; i++) {7
for (int j = colStart; j <= colEnd; j++) {8
if (grid[i][j] != val) return false;14
Node *helper(vector<vector<int>> &grid, int rowStart, int rowEnd, int colStart, int colEnd) {15
// New Node with isLeaf set to true by default16
Node *newNode = new Node(grid[rowStart][colStart], true);18
// Base Case if either the grid has only one cell or all the cell values are20
if ((rowStart == rowEnd && colStart == colEnd) ||21
areValuesSame(grid, rowStart, rowEnd, colStart, colEnd)) {25
// Set isLeaf to false as base case failed26
newNode->isLeaf = false;28
/* Consider variables rowMid and colMid to set the middle index between29
start and end of rows and columns of current grid portion*/30
int rowMid = rowStart + (rowEnd - rowStart) / 2;31
int colMid = colStart + (colEnd - colStart) / 2;33
// Recursively finding children of current node (newNode)34
newNode->topLeft = helper(grid, rowStart, rowMid, colStart, colMid);35
newNode->topRight = helper(grid, rowStart, rowMid, colMid + 1, colEnd);36
newNode->bottomLeft = helper(grid, rowMid + 1, rowEnd, colStart, colMid);37
newNode->bottomRight = helper(grid, rowMid + 1, rowEnd, colMid + 1, colEnd);42
Node *construct(vector<vector<int>> &grid) {44
return helper(grid, 0, n - 1, 0, n - 1);