leetcode427.建立四叉树
区间x0到x1和区间y0到y1都是左闭右开的
解题基本思路是先判断当前矩阵是不是全0或全1,如果是就直接返回新建的一个节点值(矩阵的统一值,叶子节点),如果不是那就新建一个节点值,非叶并且左上右上左下右下四个方向上递归创建节点
/*
// Definition for a QuadTree node.
class Node {public boolean val;public boolean isLeaf;public Node topLeft;public Node topRight;public Node bottomLeft;public Node bottomRight;public Node() {this.val = false;this.isLeaf = false;this.topLeft = null;this.topRight = null;this.bottomLeft = null;this.bottomRight = null;}public Node(boolean val, boolean isLeaf) {this.val = val;this.isLeaf = isLeaf;this.topLeft = null;this.topRight = null;this.bottomLeft = null;this.bottomRight = null;}public Node(boolean val, boolean isLeaf, Node topLeft, Node topRight, Node bottomLeft, Node bottomRight) {this.val = val;this.isLeaf = isLeaf;this.topLeft = topLeft;this.topRight = topRight;this.bottomLeft = bottomLeft;this.bottomRight = bottomRight;}
}
*/class Solution {private Node construct(int[][] grid, int x0, int y0, int x1, int y1) {for (int i = x0; i < x1; i++)for (int j = y0; j < y1; j++)if (grid[i][j] != grid[x0][y0])return new Node(true, false,construct(grid, x0, y0, (x0 + x1) / 2, (y0 + y1) / 2),construct(grid, x0, (y0 + y1) / 2, (x0 + x1) / 2, y1),construct(grid, (x0 + x1) / 2, y0, x1, (y0 + y1) / 2),construct(grid, (x0 + x1) / 2, (y0 + y1) / 2, x1, y1));return new Node(grid[x0][y0] == 1, true);}public Node construct(int[][] grid) {return construct(grid, 0, 0, grid.length, grid.length);}
}