|
1 | | -# construct_quad_tree.md |
| 1 | +# [427. Construct Quad Tree](https://leetcode.com/problems/construct-quad-tree/) |
2 | 2 |
|
| 3 | +## Approach 1: Recursive Division of Grid |
| 4 | + |
| 5 | +### Solution |
| 6 | +```java |
| 7 | +// Time Complexity: O(n^2 * log n), where n is the side length of the grid |
| 8 | +// Space Complexity: O(log n) (due to recursion stack) |
| 9 | +public class Solution { |
| 10 | + public Node construct(int[][] grid) { |
| 11 | + return buildTree(grid, 0, 0, grid.length); |
| 12 | + } |
| 13 | + |
| 14 | + private Node buildTree(int[][] grid, int x, int y, int size) { |
| 15 | + if (size == 1) { |
| 16 | + // Base case: single cell |
| 17 | + return new Node(grid[x][y] == 1, true, null, null, null, null); |
| 18 | + } |
| 19 | + |
| 20 | + int halfSize = size / 2; |
| 21 | + |
| 22 | + // Recursively divide the grid into four quadrants |
| 23 | + Node topLeft = buildTree(grid, x, y, halfSize); |
| 24 | + Node topRight = buildTree(grid, x, y + halfSize, halfSize); |
| 25 | + Node bottomLeft = buildTree(grid, x + halfSize, y, halfSize); |
| 26 | + Node bottomRight = buildTree(grid, x + halfSize, y + halfSize, halfSize); |
| 27 | + |
| 28 | + // Check if all four quadrants are leaves with the same value |
| 29 | + if (topLeft.isLeaf && topRight.isLeaf && bottomLeft.isLeaf && bottomRight.isLeaf |
| 30 | + && topLeft.val == topRight.val && topRight.val == bottomLeft.val |
| 31 | + && bottomLeft.val == bottomRight.val) { |
| 32 | + return new Node(topLeft.val, true, null, null, null, null); // Merge into one leaf |
| 33 | + } |
| 34 | + |
| 35 | + // Otherwise, create an internal node |
| 36 | + return new Node(true, false, topLeft, topRight, bottomLeft, bottomRight); |
| 37 | + } |
| 38 | +} |
| 39 | +``` |
0 commit comments