#427
Construct Quad Tree
MediumArrayDivide and ConquerTreeMatrixDivide and ConquerRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a recursive approach to divide the grid into quadrants only when necessary. By checking if the current section of the grid is uniform, we can quickly create leaf nodes and avoid unnecessary divisions.
⚙️
Algorithm
4 steps- 1Step 1: Define a recursive function that checks if the current section of the grid is uniform.
- 2Step 2: If it is uniform, create a leaf node and return it.
- 3Step 3: If not, divide the grid into four quadrants and recursively call the function for each quadrant.
- 4Step 4: Assign the resulting nodes to the corresponding children of the current node.
solution.py33 lines
1class Node:
2 def __init__(self, val=False, isLeaf=False):
3 self.val = val
4 self.isLeaf = isLeaf
5 self.topLeft = None
6 self.topRight = None
7 self.bottomLeft = None
8 self.bottomRight = None
9
10
11def construct(grid):
12 def isUniform(x1, y1, x2, y2):
13 val = grid[x1][y1]
14 for i in range(x1, x2):
15 for j in range(y1, y2):
16 if grid[i][j] != val:
17 return False, None
18 return True, val
19
20 def build(x1, y1, x2, y2):
21 uniform, val = isUniform(x1, y1, x2, y2)
22 if uniform:
23 return Node(val == 1, True)
24 mid_x = (x1 + x2) // 2
25 mid_y = (y1 + y2) // 2
26 node = Node(False, False)
27 node.topLeft = build(x1, y1, mid_x, mid_y)
28 node.topRight = build(x1, mid_y, mid_x, y2)
29 node.bottomLeft = build(mid_x, y1, x2, mid_y)
30 node.bottomRight = build(mid_x, mid_y, x2, y2)
31 return node
32
33 return build(0, 0, len(grid), len(grid))ℹ
Complexity note: The time complexity is O(n) because each cell is processed once. The space complexity is O(n) due to the recursive call stack and the nodes created for the Quad-Tree.
- 1Understanding the structure of a Quad-Tree is crucial.
- 2Recognizing when to stop recursion helps optimize the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.