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 @   Junior_bond  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示