[每日一题][找工作第32天][2025-10-24] Leetcode 101. 对称二叉树

题目

101. 对称二叉树
给你一个二叉树的根节点 root , 检查它是否轴对称。
 
示例 1:

输入:root = [1,2,2,3,4,4,3]
输出:true
示例 2:

输入:root = [1,2,2,null,3,null,3]
输出:false
 
提示:

  • 树中节点数目在范围 [1, 1000] 内
  • -100 <= Node.val <= 100
     
    进阶:你可以运用递归和迭代两种方法解决这个问题吗?

我的代码(Python)

# 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: Optional[TreeNode]) -> bool:
        if not root:
            return True
        if (root.left is None) != (root.right is None):
            return False
        if root.left is None:
            return True
        cachedNodes = []
        cachedNodes.append((root.left, root.right))
        while len(cachedNodes) != 0:
            lNode, rNode = cachedNodes.pop()
            if lNode.val != rNode.val:
                return False
            if (lNode.left is None) != (rNode.right is None):
                return False
            if lNode.left:
                cachedNodes.append((lNode.left, rNode.right))
            if (lNode.right is None) != (rNode.left is None):
                return False
            if lNode.right:
                cachedNodes.append((lNode.right, rNode.left))
        return True        

点评

递归没什么难度。
迭代主要是如何实现和管理栈,在Python里用list和元组很方便。


baddif@gmail.com

AI简历优化站

Nonpareil.me:优化简历,助力职场
开源代码

AI求职跟踪器(建设中)

开源代码

主站(建设中)

Nonpareil Me

相关平台

Github Issues / Notion / Blog

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部