LeetCode.558. 四叉树交集___分治

题目链接:

558. 四叉树交集

Solution:

  • 主要在于理解好题意,其实就是一个递归问题,具体见代码注释。

Code:

/*
// 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() {}

    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 intersect(Node quadTree1, Node quadTree2) {
        if(quadTree1.isLeaf){
            if(quadTree1.val){
                return new Node(true,true);
            }
            return new Node(quadTree2.val,quadTree2.isLeaf,quadTree2.topLeft,quadTree2.topRight,quadTree2.bottomLeft,quadTree2.bottomRight);
        }

        if(quadTree2.isLeaf){
            if(quadTree2.val){
                return new Node(true,true);
            }
            return new Node(quadTree1.val,quadTree1.isLeaf,quadTree1.topLeft,quadTree1.topRight,quadTree1.bottomLeft,quadTree1.bottomRight);
        }

        Node node1 = intersect(quadTree1.topLeft,quadTree2.topLeft);
        Node node2 = intersect(quadTree1.topRight,quadTree2.topRight);
        Node node3 = intersect(quadTree1.bottomLeft,quadTree2.bottomLeft);
        Node node4 = intersect(quadTree1.bottomRight,quadTree2.bottomRight);
        
        // 四个子节点的值要一样,且要保证他们均为叶子节点
        // 因为原先是构建的时候,而构建其实就是造的节点都为新节点,即为子节点
        if(node1.isLeaf && node2.isLeaf && node3.isLeaf && node4.isLeaf && node1.val == node2.val 
                && node1.val == node3.val && node1.val == node4.val){
                    // 成功则代表其会融合为一个新的叶子节点
                return new Node(node1.val,true);
        }

        return new Node(false,false,node1,node2,node3,node4);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

向光.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值