427.construct-quad-tree.java 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /*
  2. // Definition for a QuadTree node.
  3. class Node {
  4. public boolean val;
  5. public boolean isLeaf;
  6. public Node topLeft;
  7. public Node topRight;
  8. public Node bottomLeft;
  9. public Node bottomRight;
  10. public Node() {}
  11. public Node(boolean _val,boolean _isLeaf,Node _topLeft,Node _topRight,Node _bottomLeft,Node _bottomRight) {
  12. val = _val;
  13. isLeaf = _isLeaf;
  14. topLeft = _topLeft;
  15. topRight = _topRight;
  16. bottomLeft = _bottomLeft;
  17. bottomRight = _bottomRight;
  18. }
  19. };
  20. */
  21. class Solution {
  22. public Node construct(int[][] grid) {
  23. return construct(grid, 0, 0, grid.length);
  24. }
  25. private Node construct(int[][] grid, int x, int y, int n) {
  26. if (n == 1)
  27. return new Node(grid[y][x] == 1, true, null, null, null, null);
  28. n /= 2;
  29. Node tl = construct(grid, x, y, n);
  30. Node tr = construct(grid, x + n, y, n);
  31. Node bl = construct(grid, x, y + n, n);
  32. Node br = construct(grid, x + n, y + n, n);
  33. if (tl.isLeaf && tr.isLeaf && bl.isLeaf && br.isLeaf && tl.val == tr.val && tr.val == bl.val && bl.val == br.val)
  34. return new Node(tl.val, true, null, null, null, null);
  35. return new Node(true, false, tl, tr, bl, br);
  36. }
  37. }