← 返回 uber 的题目列表Implement / Build a QuadTree for a 2D grid with general values (not just 0/1)
类型:online_judge
Problem: Implement / Build a QuadTree (values are not limited to 0/1)
Given a 2D grid grid representing a square region, where each smallest cell contains a value (not restricted to 0/1; could be any integer), implement a QuadTree data structure from scratch and write a function to construct the QuadTree.
QuadTree rules
For any node representing a region:
The node corresponds to an axis-aligned square subregion.
If all cells in the region have the same value, the node is a leaf and stores that value.
Otherwise, the node is an internal node and the region is evenly split into 4 quadrants (top-left, top-right, bottom-left, bottom-right); recursively build the 4 children.
You should design and implement the node structure yourself (e.g., fields like isLeaf, val, topLeft, topRight, bottomLeft, bottomRight, and optionally boundary coordinates).
Input
An n x n 2D array grid (n >= 1).
Output
Return the root node of the constructed QuadTree.
Constraints / Notes
The region is a square.
Each split divides the region into four equal sub-squares.
The constructed tree must satisfy:
A node is a leaf only if all values in its region are identical.
Otherwise it must have exactly 4 children.
Sample test ideas
(Serialization is up to you, e.g., print nodes in preorder as (isLeaf, val).)
n=1: [[5]] -> root is leaf with val=5
n=2 all same: [[7,7],[7,7]] -> root is leaf val=7
n=2 all different: [[1,2],[3,4]] -> root internal, 4 leaf children 1,2,3,4
n=4 quadrant-uniform grid -> root internal, 4 leaf children
n=4 requires deeper recursion -> some quadrants must be further split
Example
Input
1
5
Output
(isLeaf=1,val=5)