As an alternative approach, you can first transform the matrix into a binary format, which can then be easily converted into a quad-tree. However, this technique is primarily applicable to matrices containing binary values and may be overly complex for matrices with larger integer values: class Node { boolean val ; boolean isLeaf ; Node topLeft , topRight , bottomLeft , bottomRight ; } public Node construct ( int [ ] [ ] grid ) { int n = grid . length ; Node result = new Node ( ) ; result . isLeaf = isLeaf ( grid , 0 , 0 , n - 1 , n - 1 ) ; if ( result . isLeaf ) { result . val = grid [ 0 ] [ 0 ] == 1 ; } else { result . topLeft = construct ( subGrid ( grid , 0 , n / 2 , 0 , n / 2 ) ) ; result . topRight = construct ( subGrid ( grid , 0 , n / 2 , n / 2 , n ) ) ; result . bottomLeft = construct ( subGrid ( grid , n / 2 , n , 0 , n / 2 ) ) ; result . bottomRight = construct ( subGrid ( grid , n / 2 , n , n / 2 , n ) ) ; } return result ; } private boolean isLeaf ( int [ ] [ ] grid , int rowStart , int rowEnd , int colStart , int colEnd ) { int first = grid [ rowStart ] [ colStart ] ; for ( int i = rowStart ; i < rowEnd ; i ++ ) { for ( int j = colStart ; j < colEnd ; j ++ ) { if ( grid [ i ] [ j ] != first ) return false ; } } return true ; } private int [ ] [ ] subGrid ( int [ ] [ ] grid , int rowStart , int rowEnd , int colStart , int colEnd ) { int [ ] [ ] result = new int [ rowEnd - rowStart ] [ colEnd - colStart ] ; for ( int i = rowStart ; i < rowEnd ; i ++ ) { for ( int j = colStart ; j < colEnd ; j ++ ) { result [ i - rowStart ] [ j - colStart ] = grid [ i ] [ j ] ; } } return result ; } In this Java code, we begin by defining the Node class, followed by the construct method that accepts the grid matrix. If the matrix can be identified as a leaf node (with all elements being identical), that value is returned. Otherwise, the grid is divided into four sections, and each is constructed individually. The isLeaf method checks if a portion of the grid can be represented as a leaf node, while the subGrid method creates a subgrid from a specified section of the original grid.