100. 相同的树

给你两棵二叉树的根节点 p 和 q ,编写一个函数来检验这两棵树是否相同。

如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

 

示例 1:


输入:p = [1,2,3], q = [1,2,3]
输出:true


示例 2:

输入:p = [1,2], q = [1,null,2]
输出:false


示例 3:


输入:p = [1,2,1], q = [1,1,2]
输出:false
 

提示:

两棵树上的节点数目都在范围 [0, 100] 内
-104 <= Node.val <= 104

dfs写法

# 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 p and not q:
            return True
        elif (not p) ^ (not q):
            return False
        
        if p.val != q.val:
            return False

        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

 

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 p and not q:
            return True
        elif not p or not q:
            return False
        
        queue1, queue2 = [p], [q]

        while queue1 and queue2:
            node1, node2 = queue1.pop(0), queue2.pop(0)
            if node1.val != node2.val:
                return False

            if (not node1.left) ^ (not node2.left):
                return False
            elif (not node1.right) ^ (not node2.right):
                return False

            if node1.left and node2.left:
                queue1.append(node1.left)            
                queue2.append(node2.left)            

            if node1.right and node2.right:
                queue1.append(node1.right)            
                queue2.append(node2.right)        

        return True

 

posted @ 2021-12-09 11:12  风不再来  阅读(18)  评论(0编辑  收藏  举报