Skip to main content
All Questions

Convert a matrix to a quad tree.

Medium
Unlock detailed company stats for this questionUpgrade

Given an n x n grid of 0s and 1s, where n is a power of 2, build a quad tree that represents it and return its root.

Each node of a quad tree covers a square region of the grid and has six fields: val, is_leaf and four children top_left, top_right, bottom_left and bottom_right. The class is defined for you in the starter code.

  • If every cell in the region has the same value, the node is a leaf: set is_leaf to true, set val to true for 1s or false for 0s and leave the children empty.
  • Otherwise, the node isn't a leaf. Split the region into four equal quadrants, build a child for each and set val to anything.

The tests write your tree in preorder as a list of numbers. A leaf is written as its value, 0 or 1. A split node is written as -1, followed by its four children in the order top-left, top-right, bottom-left, bottom-right.

Example 1

Input: grid = [[0, 1], [1, 0]] Output: [-1, 0, 1, 1, 0]

The cells differ, so the root splits into four single-cell leaves.

Example 2

Input: grid = [[1, 1, 0, 0], [1, 1, 0, 0], [0, 0, 1, 1], [0, 0, 1, 0]] Output: [-1, 1, 0, 0, -1, 1, 1, 1, 0]

The top-left, top-right and bottom-left quadrants are uniform, so each is one leaf. The bottom-right quadrant has a 0 in one corner, so it splits again.

Constraints

  • n == grid.length == grid[i].length
  • n is 2^x for some 0 <= x <= 6.
  • Each cell is 0 or 1.

Related courses

Course

Machine Learning Engineer Interview Prep

Land your dream machine learning role at Meta, Google, Amazon, Apple, Microsoft, Nvidia, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Explore ML system design, core concepts, coding, behavioral interviews, and more.

Course

Behavioral Interviews: A Practical Guide for Engineers

Get offers at the level you deserve. Prep for senior+ behavioral interviews at FAANG and Tier-1 companies. Made with staff and principal engineers from Meta, Netflix, Google, and more. Avoid downleveling, elevate past projects, and stop sounding like a robot.