lhl
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
  • python

  • leetcode

    • 数组

    • 位运算

    • 动态规划

    • 链表

    • 栈

    • 树

      • 94.二叉树的中序遍历
      • 100.相同的树
      • 101.对称二叉树
      • 226.翻转二叉树
      • 543. 二叉树的直径
  • 软件测试

  • Git

  • linux

  • 产品

  • MySql

  • docker

  • leetcode
  • tree
2023-04-29

对称二叉树

https://leetcode-cn.com/submissions/detail/305476984/ (opens new window) 需要注意的点 1.迭代 2.递归

# 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
        
        left = root.left
        right = root.right

        if (not left and right) or (not right and left):
            return False

        q = [left, right]

        while q:
            n1 = q.pop(0)
            n2 = q.pop(0)

            if not n1 and not n2:
                continue

            if not n1 or not n2:
                return False
            
            if n1.val != n2.val:
                return False
            
            q.append(n1.left)
            q.append(n2.right)
            q.append(n1.right)
            q.append(n2.left)

        return True
# 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

        def reverseTree(left: TreeNode, right: TreeNode)-> bool:
            if not left or not right:
                return left == right
            
            if left.val != right.val:
                return False

            return (reverseTree(left.left, right.right) and reverseTree(left.right, right.left)) 

        return reverseTree(root.left, root.right)


100.相同的树
226.翻转二叉树

← 100.相同的树 226.翻转二叉树→

最近更新
01
lhl learn notes
02
filter
06-09
03
decorator
06-09
更多文章>
Theme by Vdoing
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式