15% off all plans & roadmaps Use code
See plansProblem editorial
Implement Solution.construct(grid) to build a quad tree representing the binary matrix grid. The matrix has n rows and n columns. A node represents a square region of the matrix and has an isLeaf flag, a val, and up to four children in this order: topLeft, topRight, bottomLeft, and bottomRight.
Construct Quad Tree is a Tree Traversal Patterns (DFS & BFS) problem, in the Recursive Preorder Traversal subpattern. The pattern covers preorder, inorder, level order traversal, LCA, and serialization
The reference solution runs in O(n^2) time and O(n^2) space.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Construct Quad Tree is a Tree Traversal Patterns (DFS & BFS) problem, in the Recursive Preorder Traversal subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.