"""
# Definition for a QuadTree node.
class Node:
    def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
        self.val = val
        self.isLeaf = isLeaf
        self.topLeft = topLeft
        self.topRight = topRight
        self.bottomLeft = bottomLeft
        self.bottomRight = bottomRight
"""

class Solution:
    def construct(self, grid: List[List[int]]) -> 'Node':
        n = len(grid)
        def check_is_leaf(row_start,row_end,column_start,column_end):
            x = grid[row_start][column_start]
            for i in range(row_start, row_end + 1):
                for j in range(column_start, column_end + 1):
                    if grid[i][j] != x:
                        return 0
            return 1
        def dfs(dim, row, column,node):
            isLeaf = check_is_leaf(row,row+dim -1 , column, column + dim - 1)
            node.isLeaf= isLeaf
            if isLeaf==1:
                node.val=grid[row][column]
            else:
                node.val = 1
                top_left = Node()
                node.topLeft = dfs(dim // 2, row, column, top_left)
                top_right = Node()
                node.topRight = dfs(dim // 2, row, column + dim // 2, top_right)
                bottom_left = Node()
                node.bottomLeft = dfs(dim // 2, row + dim // 2, column, bottom_left)
                bottom_right = Node()
                node.bottomRight = dfs(dim // 2, row + dim // 2, column + dim // 2, bottom_right)
            return node
        root = Node()
        root = dfs(n,0,0,root)
        return root