Practice/Uber/Leetcode 427. Construct Quad Tree
CodingOptional
You are given an n × n binary matrix where n is a power of 2 (the matrix contains only 0s and 1s). Your task is to build a quadtree representation of this matrix.
A quadtree is a tree data structure where each internal node has exactly four children. For this problem, each node represents a rectangular region of the matrix and has the following properties:
val: A boolean representing the value of the region (true for 1, false for 0). Only meaningful for leaf nodes.isLeaf: A boolean indicating whether the node is a leaf (true) or internal node (false).topLeft, topRight, bottomLeft, bottomRight: Four child nodes representing the four quadrants.The construction follows these rules:
isLeaf = true and val equal to that value.isLeaf = false, then recursively divide the region into four equal quadrants and build the tree for each quadrant.The quadrants are divided in this order: top-left, top-right, bottom-left, bottom-right.
Example 1:
Input: grid = [[1,1],[1,1]] Output: Node(isLeaf=True, val=True) Explanation: The entire 2×2 grid contains only 1s, so we return a single leaf node with value true.
Example 2:
Input: grid = [[0]] Output: Node(isLeaf=True, val=False) Explanation: A 1×1 grid is always a leaf node. Since the cell is 0, val is false.
Example 3:
Input: grid = [[1,0],[0,1]] Output: Node(isLeaf=False, val=True, topLeft=Node(isLeaf=True, val=True), topRight=Node(isLeaf=True, val=False), bottomLeft=Node(isLeaf=True, val=False), bottomRight=Node(isLeaf=True, val=True)) Explanation: The grid has mixed values, so it splits into four 1×1 quadrants, each becoming a leaf.
Example 4:
Input: grid = [[1,1,0,0],[1,1,0,0],[0,0,1,1],[0,0,1,1]] Output: Node(isLeaf=False, val=True, topLeft=Node(isLeaf=True, val=True), topRight=Node(isLeaf=True, val=False), bottomLeft=Node(isLeaf=True, val=False), bottomRight=Node(isLeaf=True, val=True)) Explanation: Each 2×2 quadrant is uniform, so each becomes a leaf node.