面试150 对称二叉树

思路

联想递归三部曲:传入参数、遍历方式、返回什么。本题联想到先序遍历的方式,需要遍历整颗二叉树,最后返回的是一个布尔值。然后我们需要传入的是左子树和左子树的节点,然后分别进行比较。

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:
        def compare(left,right):
            if left==None and right==None:
                return True
            elif left==None and right!=None:
                return False
            elif left!=None and right==None:
                return False
            elif left.val!=right.val:
                return False
            Left=compare(left.left,right.right)#比较左子树的左孩子和右子树的右孩子
            Right=compare(left.right,right.left)#比较左子树的右孩子与右子树的左孩子
            return Left and Right
        if not root:
            return True
        return compare(root.left,root.right)
            
相关推荐
漫随流水1 天前
leetcode算法(515.在每个树行中找最大值)
数据结构·算法·leetcode·二叉树
漫随流水1 天前
leetcode算法(429.N叉树的层序遍历)
数据结构·算法·leetcode·二叉树
漫随流水1 天前
leetcode算法(116.填充每个节点的下一个右侧节点指针)
数据结构·算法·leetcode·二叉树
R-G-B2 天前
BM28 二叉树的最大深度
数据结构·算法·二叉树·bm28·二叉树的最大深度
漫随流水2 天前
leetcode算法(111.二叉树的最小深度)
数据结构·算法·leetcode·二叉树
星火开发设计2 天前
二叉树详解及C++实现
java·数据结构·c++·学习·二叉树·知识·期末考试
漫随流水2 天前
leetcode算法(637.二叉树的层平均值)
数据结构·算法·leetcode·二叉树
漫随流水2 天前
leetcode算法(102.二叉树的层序遍历)
数据结构·算法·leetcode·二叉树
漫随流水3 天前
leetcode算法(二叉树的层序遍历Ⅱ)
数据结构·算法·leetcode·二叉树
漫随流水3 天前
leetcode算法(199.二叉树的右视图)
数据结构·算法·leetcode·二叉树