classSolution{publicNodeconstruct(int[][] grid){returndfs(grid, grid.length,0,0);}privateNodedfs(int[][] grid,int n,int r,int c){boolean allSame =true;// Check if all the values in the current area are the samefor(int i =0; i < n;++i){for(int j =0; j < n;++j){// Not the same, comparing to the original cellif(grid[r][c]!= grid[r + i][c + j]){
allSame =false;break;}}}// All the same! This could be a nodeif(allSame)returnnewNode(grid[r][c]!=0,true);// Not the same, so split the square into squares
n = n /2;// Obtain each quadrantNode topLeft =dfs(grid, n, r, c);Node topRight =dfs(grid, n, r, c + n);Node bottomLeft =dfs(grid, n, r + n, c);Node bottomRight =dfs(grid, n, r + n, c + n);// Build the treereturnnewNode(false,false, topLeft, topRight, bottomLeft, bottomRight);}}