面试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)
            
相关推荐
旖-旎13 天前
《LeetCode 695 岛屿的最大面积 FloodFill DFS 解法》
c++·算法·力扣·深度优先遍历·floodfill
Irissgwe13 天前
map/set/multimap/multiset 的底层逻辑与实现
数据结构·c++·算法·二叉树·stl·c·红黑树
Irissgwe13 天前
AVL树详解
数据结构·c++·算法·二叉树·c·二叉搜索树·avl
Irissgwe14 天前
数据结构-二叉树
数据结构·c++·二叉树·c·
少司府20 天前
C++进阶:红黑树
开发语言·数据结构·c++·b树·二叉树·红黑树
少司府20 天前
C++进阶:AVL树
开发语言·数据结构·c++·二叉树·avl树
8Qi822 天前
LeetCode 337:打家劫舍 III(House Robber III)—— 题解 ✅
算法·leetcode·二叉树·动态规划
8Qi823 天前
LeetCode 235. 二叉搜索树的最近公共祖先(LCA)
算法·leetcode·二叉树·递归·二叉搜索树·lca·迭代
hope_wisdom23 天前
C/C++数据结构之二叉树基础
c语言·数据结构·c++·二叉树
HZ·湘怡24 天前
二叉树 1
数据结构·算法·二叉树·