leetcode相同的树

给定两个二叉树,编写一个函数来检验它们是否相同。
如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
在这里插入图片描述
先来迭代:

from collections import deque
class Solution(object):
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        def check(p, q):
            if not p and not q:
                return True
            if not q or not p:
                return False
            if p.val != q.val:
                return False
            else:
                return True
        l=deque([(p,q),])
        while l:
            p,q=l.popleft()
            if check(p,q):
                if p :
                    l.append((p.left,q.left))
                    l.append((p.right,q.right))
            else :
                return False
        return True

迭代在这里看起来特别麻烦,还用到了一个队列l。
还是推荐递归。

class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if not p and not q:
            return True
        if not p or not q:
            return False
        if p.val!=q.val:
            return False
        else:
            return self.isSameTree(p.left,q.left) and self.isSameTree(p.right, q.right)
发布了29 篇原创文章 · 获赞 28 · 访问量 286

猜你喜欢

转载自blog.csdn.net/weixin_45398265/article/details/104979826