Leetcode 558. Quad Tree Intersection

思路:

计算1和2两个节点的运算结果,分两种情况:

(1)1为叶节点:若1的节点值为False,返回节点2;否则返回节点1

(2)1不为叶节点:

          A. 若2为叶节点且节点值为False,返回节点1;否则返回节点2

          B. 若2不为叶节点,迭代计算1和2的四个子节点的结果,分别赋值给节点1的四个节点

               这里需要注意,子节点计算完成后需要判断四个子节点若都是叶子节点且取值相同,需合并为一个叶子节点

"""
# Definition for a QuadTree node.
class Node(object):
    def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
        self.val = val
        self.isLeaf = isLeaf
        self.topLeft = topLeft
        self.topRight = topRight
        self.bottomLeft = bottomLeft
        self.bottomRight = bottomRight
"""
def qd(quadTree1, quadTree2):
    if quadTree1.isLeaf:
        return quadTree1 if quadTree1.val else quadTree2
    else:
        if quadTree2.isLeaf:        
                return quadTree2 if quadTree2.val else quadTree1
        else:
            quadTree1.topLeft = qd(quadTree1.topLeft,quadTree2.topLeft)
            quadTree1.topRight = qd(quadTree1.topRight,quadTree2.topRight)
            quadTree1.bottomLeft = qd(quadTree1.bottomLeft,quadTree2.bottomLeft)
            quadTree1.bottomRight = qd(quadTree1.bottomRight,quadTree2.bottomRight)
            if quadTree1.topLeft.isLeaf and quadTree1.topRight.isLeaf and quadTree1.bottomLeft.isLeaf and quadTree1.bottomRight.isLeaf:
                if quadTree1.topLeft.val and quadTree1.topRight.val and quadTree1.bottomLeft.val and quadTree1.bottomRight.val:
                    return Node(True,True,None,None,None,None)
                elif not quadTree1.topLeft.val and not quadTree1.topRight.val and not quadTree1.bottomLeft.val and not quadTree1.bottomRight.val:
                    return Node(False,True,None,None,None,None)
    quadTree1.val = False
    return quadTree1

class Solution(object):
    def intersect(self, quadTree1, quadTree2):
        """
        :type quadTree1: Node
        :type quadTree2: Node
        :rtype: Node
        """
        return qd(quadTree1, quadTree2)

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值