leedcode 对称二叉树

迭代法:
# 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 isSymmetric(self, root) :
        queue=[root,root]#等效为比较两棵树
        if not root:
            return  True
        while queue:
            tree_1=queue.pop(0)#第一棵树
            tree_2=queue.pop(0)#第二棵树
            if not tree_1 and not tree_2:#两颗树都为空
                continue
            elif not tree_1 or not tree_2:#单论这句的意思是有一个为空  但上面排除了两颗都为空的情况
                return False
            elif tree_1.val!=tree_2.val:#值不相等
                return False
            queue.append(tree_1.left)
            queue.append(tree_2.right)
            queue.append(tree_1.right)
            queue.append(tree_2.left)
        return True

递归法:

from typing import Optional

class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        # 如果根节点为空,返回 True,因为空树视为对称
        if not root:
            return True
        # 调用 isMirror 函数,传入左子树和右子树进行比较
        return self.isMirror(root.left, root.right)

    def isMirror(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        # 如果两棵树的当前节点都为空,说明它们是对称的
        if not p and not q:
            return True
        # 如果其中一个节点为空而另一个不为空,说明不对称
        elif not p or not q:
            return False
        # 如果两个节点都不为空,但它们的值不相等,说明不对称
        elif p.val != q.val:
            return False
        # 递归调用 isMirror 函数,比较左子树的左节点和右子树的右节点,以及左子树的右节点和右子树的左节点是否对称
        # 返回递归调用的结果,表示两个子树是否对称
        return self.isMirror(p.left, q.right) and self.isMirror(p.right, q.left)

 

posted @ 2024-02-05 18:24  Junior_bond  阅读(7)  评论(0)    收藏  举报