0
点赞
收藏
分享

微信扫一扫

力扣每日训练:100题相同的树

九点韶留学 2022-01-31 阅读 60

100. 相同的树 - 力扣(LeetCode) (leetcode-cn.com)

这个题题意很简单,就是判断两颗树是不是相同。我想到的办法就是用BFS遍历一个遍,把一个树的左节点放到一个列表内,所有有右节点放到一个节点内,一个树的一定位置的左节点和另一个树内所有一定位置右节点相等就说明两个树是相等的。

但是还有一个关键问题就是左右树的深度一定要相等,要不然有特殊情况会导致认证不通过。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if not q and not p:
            return True
        if not q: return False
        if not p: return False
        lst_left1 = [p.val]
        lst_right1 = [p.val]
        lst_left2 = [q.val]
        lst_right2 = [q.val]
        deepth1 = 1
        deepth2 = 1
        queue = [(p, deepth1)]
        while queue:
            root, deepth1 = queue.pop(0)
            if root.left:
                queue.append((root.left, deepth1 + 1))
                lst_left1.append(root.left.val)
            if root.right:
                queue.append((root.right, deepth1 + 1))
                lst_right1.append(root.right.val)
        queue = [(q, deepth2)]
        while queue:
            root, deepth2 = queue.pop(0)
            if root.left:
                queue.append((root.left, deepth2 + 1))
                lst_left2.append(root.left.val)
            if root.right:
                queue.append((root.right, deepth2 + 1))
                lst_right2.append(root.right.val) 
        if tuple(lst_left1) == tuple(lst_left2) and tuple(lst_right1) == tuple(lst_right2) and deepth1 == deepth2:
            return True
        else:
            return False
举报

相关推荐

0 条评论