java 实现 四叉树_Java实现 LeetCode 427 建立四叉树

427. 建立四叉树

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

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

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

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

150a131e8af10bd447a62ad448991cbe.png

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

d9268a55da8839b61d30b7e582f5b417.png

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

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

5b84456a63621a0b339b9cce3d5c5898.png

提示:

N 将小于 1000 且确保是 2 的整次幂。

其实这个题有一些像前段时间看到得棋盘覆盖

/*

// 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 {

public Node construct(int[][] grid) {

return construct(grid, 0, grid.length - 1, 0, grid.length - 1);

}

private Node construct(int[][] grid, int top, int bottom, int left, int right) {

for (int i = top; i <= bottom; i++) {

for (int j = left; j <= right; j++) {

if (grid[i][j] != grid[top][left]) {

Node node = new Node(false, false);

int mid1 = top + ((bottom - top) >> 1), mid2 = left + ((right - left) >> 1);

node.topLeft = construct(grid, top, mid1, left, mid2);

node.topRight = construct(grid, top, mid1, mid2 + 1, right);

node.bottomLeft = construct(grid, mid1 + 1, bottom, left, mid2);

node.bottomRight = construct(grid, mid1 + 1, bottom, mid2 + 1, right);

return node;

}

}

}

return new Node(grid[top][left] == 1, true);

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值