|
| 1 | +package quad_tree; |
| 2 | + |
| 3 | +/** |
| 4 | + * Description: https://leetcode.com/problems/construct-quad-tree |
| 5 | + * Difficulty: Medium |
| 6 | + * Time complexity: O(n^2) |
| 7 | + * Space complexity: O(log n) |
| 8 | + */ |
| 9 | +public class ConstructQuadTree { |
| 10 | + |
| 11 | + public Node construct(int[][] grid) { |
| 12 | + return construct(grid, 0, 0, grid.length); |
| 13 | + } |
| 14 | + |
| 15 | + private Node construct(int[][] grid, int x, int y, int length) { |
| 16 | + if (length == 1) { |
| 17 | + // single cell is always a leaf |
| 18 | + return new Node(grid[x][y] == 1, true); |
| 19 | + } |
| 20 | + |
| 21 | + Node topLeft = construct(grid, x, y, length / 2); |
| 22 | + Node topRight = construct(grid, x, y + length / 2, length / 2); |
| 23 | + Node bottomLeft = construct(grid, x + length / 2, y, length / 2); |
| 24 | + Node bottomRight = construct(grid, x + length / 2, y + length / 2, length / 2); |
| 25 | + |
| 26 | + if (topLeft.isLeaf && topRight.isLeaf && bottomLeft.isLeaf && bottomRight.isLeaf |
| 27 | + && topLeft.val == topRight.val |
| 28 | + && bottomLeft.val == bottomRight.val |
| 29 | + && topLeft.val == bottomLeft.val) { |
| 30 | + // all children are leaves with the same value -> root is leaf |
| 31 | + return new Node(topLeft.val, true); |
| 32 | + } |
| 33 | + |
| 34 | + return new Node(false, false, topLeft, topRight, bottomLeft, bottomRight); |
| 35 | + } |
| 36 | + |
| 37 | + private static class Node { |
| 38 | + |
| 39 | + private final boolean val; |
| 40 | + private final boolean isLeaf; |
| 41 | + private final Node topLeft; |
| 42 | + private final Node topRight; |
| 43 | + private final Node bottomLeft; |
| 44 | + private final Node bottomRight; |
| 45 | + |
| 46 | + public Node(boolean val, boolean isLeaf) { |
| 47 | + this.val = val; |
| 48 | + this.isLeaf = isLeaf; |
| 49 | + this.topLeft = null; |
| 50 | + this.topRight = null; |
| 51 | + this.bottomLeft = null; |
| 52 | + this.bottomRight = null; |
| 53 | + } |
| 54 | + |
| 55 | + public Node(boolean val, boolean isLeaf, Node topLeft, Node topRight, Node bottomLeft, Node bottomRight) { |
| 56 | + this.val = val; |
| 57 | + this.isLeaf = isLeaf; |
| 58 | + this.topLeft = topLeft; |
| 59 | + this.topRight = topRight; |
| 60 | + this.bottomLeft = bottomLeft; |
| 61 | + this.bottomRight = bottomRight; |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments