KatInterview

772. Construct Quad Tree

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method Explanation

This problem asks us to build a Quad-Tree from a given n x n grid. The structure of a Quad-Tree is inherently recursive, which guides us toward a recursive solution.

Solution

Construct Quad Tree in Python

"""
# 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 build(r: int, c: int, size: int) -> 'Node':
            # Check if the current subgrid is homogeneous.
            is_homogeneous = True
            first_val = grid[r][c]
            for i in range(r, r + size):
                for j in range(c, c + size):
                    if grid[i][j] != first_val:
                        is_homogeneous = False
                        break
                if not is_homogeneous:
                    break
            
            if is_homogeneous:
                # If homogeneous, create a leaf node.
                return Node(first_val == 1, True, None, None, None, None)
            else:
                # If not homogeneous, create an internal node and recurse for its children.
                half = size // 2
                top_left = build(r, c, half)
                top_right = build(r, c + half, half)
                bottom_left = build(r + half, c, half)
                bottom_right = build(r + half, c + half, half)
                
                # The value for an internal node can be anything, so we can just use True.
                return Node(True, False, top_left, top_right, bottom_left, bottom_right)

        return build(0, 0, n)

Construct Quad Tree in Java

/*
// Definition for a QuadTree node.
class Node {
    public boolean val;
    public boolean isLeaf;
    public Node topLeft;
    public Node topRight;
    public Node bottomLeft;
    public Node bottomRight;

    
    public Node() {
        this.val = false;
        this.isLeaf = false;
        this.topLeft = null;
        this.topRight = null;
        this.bottomLeft = null;
        this.bottomRight = null;
    }
    
    public Node(boolean val, boolean isLeaf) {
        this.val = val;
        this.isLeaf = isLeaf;
        this.topLeft = null;
        this.topRight = null;
        this.bottomLeft = null;
        this.bottomRight = null;
    }
    
    public Node(boolean val, boolean isLeaf, Node topLeft, Node topRight, Node bottomLeft, Node bottomRight) {
        this.val = val;
        this.isLeaf = isLeaf;
        this.topLeft = topLeft;
        this.topRight = topRight;
        this.bottomLeft = bottomLeft;
        this.bottomRight = bottomRight;
    }
}
*/

class Solution {
    public Node construct(int[][] grid) {
        return build(grid, 0, 0, grid.length);
    }
    
    private Node build(int[][] grid, int r, int c, int size) {
        // Check if the current subgrid is homogeneous.
        boolean isHomogeneous = true;
        int firstVal = grid[r][c];
        for (int i = r; i < r + size; i++) {
            for (int j = c; j < c + size; j++) {
                if (grid[i][j] != firstVal) {
                    isHomogeneous = false;
                    break;
                }
            }
            if (!isHomogeneous) {
                break;
            }
        }
        
        if (isHomogeneous) {
            // If homogeneous, create a leaf node.
            return new Node(firstVal == 1, true);
        } else {
            // If not homogeneous, create an internal node and recurse for its children.
            int half = size / 2;
            Node topLeft = build(grid, r, c, half);
            Node topRight = build(grid, r, c + half, half);
            Node bottomLeft = build(grid, r + half, c, half);
            Node bottomRight = build(grid, r + half, c + half, half);
            
            // The value for an internal node can be anything, so we can just use true.
            return new Node(true, false, topLeft, topRight, bottomLeft, bottomRight);
        }
    }
}

Construct Quad Tree in C++

/*
// Definition for a QuadTree node.
class Node {
public:
    bool val;
    bool isLeaf;
    Node* topLeft;
    Node* topRight;
    Node* bottomLeft;
    Node* bottomRight;
    
    Node() {
        val = false;
        isLeaf = false;
        topLeft = NULL;
        topRight = NULL;
        bottomLeft = NULL;
        bottomRight = NULL;
    }
    
    Node(bool _val, bool _isLeaf) {
        val = _val;
        isLeaf = _isLeaf;
        topLeft = NULL;
        topRight = NULL;
        bottomLeft = NULL;
        bottomRight = NULL;
    }
    
    Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) {
        val = _val;
        isLeaf = _isLeaf;
        topLeft = _topLeft;
        topRight = _topRight;
        bottomLeft = _bottomLeft;
        bottomRight = _bottomRight;
    }
};
*/

class Solution {
public:
    Node* construct(vector<vector<int>>& grid) {
        int n = grid.size();
        return build(grid, 0, 0, n);
    }

private:
    Node* build(vector<vector<int>>& grid, int r, int c, int size) {
        // Check if the current subgrid is homogeneous.
        bool isHomogeneous = true;
        int firstVal = grid[r][c];
        for (int i = r; i < r + size; ++i) {
            for (int j = c; j < c + size; ++j) {
                if (grid[i][j] != firstVal) {
                    isHomogeneous = false;
                    break;
                }
            }
            if (!isHomogeneous) {
                break;
            }
        }

        if (isHomogeneous) {
            // If homogeneous, create a leaf node.
            return new Node(firstVal == 1, true);
        }
        
        // If not homogeneous, create an internal node and recurse for its children.
        int half = size / 2;
        Node* topLeft = build(grid, r, c, half);
        Node* topRight = build(grid, r, c + half, half);
        Node* bottomLeft = build(grid, r + half, c, half);
        Node* bottomRight = build(grid, r + half, c + half, half);
        
        // The value for an internal node can be anything, so we can just use true.
        return new Node(true, false, topLeft, topRight, bottomLeft, bottomRight);
    }
};

Construct Quad Tree in TypeScript

/**
 * Definition for _Node.
 * class _Node {
 *     val: boolean
 *     isLeaf: boolean
 *     topLeft: _Node | null
 * 	topRight: _Node | null
 * 	bottomLeft: _Node | null
 * 	bottomRight: _Node | null
 * 	constructor(val?: boolean, isLeaf?: boolean, topLeft?: _Node, topRight?: _Node, bottomLeft?: _Node, bottomRight?: _Node) {
 *         this.val = (val===undefined ? false : val)
 *         this.isLeaf = (isLeaf===undefined ? false : isLeaf)
 *         this.topLeft = (topLeft===undefined ? null : topLeft)
 *         this.topRight = (topRight===undefined ? null : topRight)
 *         this.bottomLeft = (bottomLeft===undefined ? null : bottomLeft)
 *         this.bottomRight = (bottomRight===undefined ? null : bottomRight)
 *   }
 * }
 */


function construct(grid: number[][]): _Node | null {
    const n = grid.length;
    if (n === 0) return null;

    function build(r: number, c: number, size: number): _Node {
        // Check if the current subgrid is homogeneous.
        let isHomogeneous = true;
        const firstVal = grid[r][c];
        for (let i = r; i < r + size; i++) {
            for (let j = c; j < c + size; j++) {
                if (grid[i][j] !== firstVal) {
                    isHomogeneous = false;
                    break;
                }
            }
            if (!isHomogeneous) break;
        }

        if (isHomogeneous) {
            // If homogeneous, create a leaf node.
            return new _Node(firstVal === 1, true);
        } else {
            // If not homogeneous, create an internal node and recurse for its children.
            const half = size / 2;
            const topLeft = build(r, c, half);
            const topRight = build(r, c + half, half);
            const bottomLeft = build(r + half, c, half);
            const bottomRight = build(r + half, c + half, half);
            
            // The value for an internal node can be anything, so we can just use true.
            return new _Node(true, false, topLeft, topRight, bottomLeft, bottomRight);
        }
    }

    return build(0, 0, n);
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.