力扣Hot100--106.对称二叉树
力扣Hot100–106.对称二叉树
要求:给你一个二叉树的根节点 root , 检查它是否轴对称。
明确概念:一棵树是对称的,当且仅当它的左子树和右子树是镜像对称的,所以判断是否是对称二叉树,其实就是判断根节点的左右孩子是否是翻转对称
用递归–后序遍历解法:
1、比较外侧:左子树的左节点 vs 右子树的右节点
2、比较内侧:左子树的右节点 vs 右子树的左节点
3、当前节点值必须相等
# 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 root is None:return True # 空def compare(left,right):if left is None and right is not None: return Falseelif left is not None and right is None: return Falseelif left is None and right is None: return Trueelif left.val != right.val: return False outside = compare(left.left,right.right)inside = compare(left.right,right.left)result = outside and insidereturn resultresult = compare(root.left,root.right)return result