101. Symmetric Binary Tree



101. Symmetric Binary Tree (Easy) 对称二叉树

题干

Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

Example 1:

img

Input: root = [1,2,2,3,4,4,3]
Output: true

Example 2:

img

Input: root = [1,2,2,null,3,null,3]
Output: false

Constraints:

Follow up: Could you solve it both recursively and iteratively?

解法

递归解法

核心思路:将根节点的左右子树递归对称对比,单个节点的对比包含以下规则:

递归实现:

两个节点的val对比属于终止条件,并不是中节点的比较,因为节点的比较,除了val之外,还有left和right的对比。

单层核心逻辑,左右中是后序遍历。

# 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
        return self.isSame(root.left, root.right)
    
    def isSame(self, node_01: Optional[TreeNode], node_02: Optional[TreeNode]) -> bool:
        # 终止条件
        if not node_01 and not node_02:
            return True
        if not node_01 or not node_02:
            return False
        if node_01.val != node_02.val:
            return False
        
        # 后序处理,左右中(中隐藏在return的逻辑里面了)
        # 注意,中是指中节点,当前节点的val对比并不是中节点完整的逻辑对比,所以不算中
        if not self.isSame(node_01.left, node_02.right):
            return False
        if not self.isSame(node_01.right, node_02.left):
            return False
        return True