1. 程式人生 > >Leetcode 427.建立四叉樹

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 }