JAVA程序设计:建立四叉树(LeetCode:427)

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

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

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

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

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

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

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

提示:

N 将小于 1000 且确保是 2 的整次幂。
如果你想了解更多关于四叉树的知识,你可以参考这个 wiki 页面

思路:沙雕题意,看了半天不知道在说啥,看了评论区才懂,其实就是让你构建一棵树,每个结点有四个孩子(子树),并且这四个子树待是权值一样的。。。。呢就是递归遍历一遍就ok了。

class Node {
    public boolean val;
    public boolean isLeaf;
    public Node topLeft;
    public Node topRight;
    public Node bottomLeft;
    public Node bottomRight;

    public Node() {}

    public Node(boolean _val,boolean _isLeaf,Node _topLeft,Node _topRight,Node _bottomLeft,Node _bottomRight) {
        val = _val;
        isLeaf = _isLeaf;
        topLeft = _topLeft;
        topRight = _topRight;
        bottomLeft = _bottomLeft;
        bottomRight = _bottomRight;
    }
};

class Solution {
    public Node construct(int[][] grid) {
        return find(grid,0,grid.length-1,0,grid.length-1);
    }
    
    private Node find(int[][] grid,int startrow,int endrow,int startcol,int endcol) {
    	boolean val;
    	val=grid[startrow][startcol]==0?false:true;
    	Node root=null;
    	if(isLeaf(grid,startrow,endrow,startcol,endcol))
    		root=new Node(val,true,null,null,null,null);
    	else {
    		root=new Node(val,false,null,null,null,null);
    		root.topLeft=find(grid,startrow,startrow+(endrow-startrow)/2,startcol,startcol+(endcol-startcol)/2);
    		root.bottomLeft=find(grid,startrow+(endrow-startrow)/2+1,endrow,startcol,startcol+(endcol-startcol)/2);
    		root.topRight=find(grid,startrow,startrow+(endrow-startrow)/2,startcol+(endcol-startcol)/2+1,endcol);
    		root.bottomRight=find(grid,startrow+(endrow-startrow)/2+1,endrow,startcol+(endcol-startcol)/2+1,endcol);
    	}
    	return root;
    }
    
    private boolean isLeaf(int[][] grid,int startrow,int endrow,int startcol,int endcol) {
    	int now=grid[startrow][startcol];
    	for(int i=startrow;i<=endrow;i++)
    		for(int j=startcol;j<=endcol;j++)
    			if(grid[i][j]!=now)
    				return false;
    	return true;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值