Leetcode 427.建立四叉树

建立四叉树

我们想要使用一棵四叉树来储存一个 N x N 的布尔值网络。网络中每一格的值只会是真或假。树的根结点代表整个网络。对于每个结点, 它将被分等成四个孩子结点直到这个区域内的值都是相同的.

每个结点还有另外两个布尔变量: isLeaf 和 val。isLeaf 当这个节点是一个叶子结点时为真。val 变量储存叶子结点所代表的区域的值。

你的任务是使用一个四叉树表示给定的网络。下面的例子将有助于你理解这个问题:

给定下面这个8 x 8 网络,我们将这样建立一个对应的四叉树:

由上文的定义,它能被这样分割:

   

对应的四叉树应该像下面这样,每个结点由一对 (isLeaf, val) 所代表.

对于非叶子结点,val 可以是任意的,所以使用 * 代替。

提示:

  1. N 将小于 1000 且确保是 2 的整次幂。
  2. 如果你想了解更多关于四叉树的知识,你可以参考这个 wiki 页面。
 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 
11     public Node() {}
12 
13     public Node(boolean _val,boolean _isLeaf,Node _topLeft,Node _topRight,Node _bottomLeft,Node _bottomRight) {
14         val = _val;
15         isLeaf = _isLeaf;
16         topLeft = _topLeft;
17         topRight = _topRight;
18         bottomLeft = _bottomLeft;
19         bottomRight = _bottomRight;
20     }
21 };
22 */
23 class Solution {
24     public Node construct(int[][] grid) {
25         return build(grid,0,0,grid.length);
26     }
27 
28     public Node build(int[][] grid,int x,int y,int len){
29         if(len<=0) return null;
30         for(int i=x;i<x+len;++i){
31             for(int j=y;j<y+len;++j){
32                 if(grid[i][j]!=grid[x][y]){
33                     return new Node(true,false,build(grid,x,y,len/2),
34                             build(grid,x,y+len/2,len/2),
35                             build(grid,x+len/2,y,len/2),
36                             build(grid,x+len/2,y+len/2,len/2));
37                 }
38             }
39         }
40         return new Node(grid[x][y]==1,true,null,null,null,null);
41     }
42 }
原文地址:https://www.cnblogs.com/kexinxin/p/10242226.html