题目描述说,最好是能用递归或迭代做
其实二叉树镜面对称,可以划分为其左子树与右子树对称
而后,比较两棵树是否对称时,相当于比较:
① A子树的左子树与B子树的右子树是否对称
② A子树的右子树与B子树的左子树是否对称
同时成立则说明两棵树对称
分析到这里,解题就比较简单了
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def compare(tree1: TreeNode, tree2: TreeNode):
if tree1 is None or tree2 is None:
if tree1 is None and tree2 is None:
return True
else:
return False
if tree1.val != tree2.val:
return False
x = compare(tree1.left, tree2.right)
y = compare(tree1.right, tree2.left)
return x and y
if root is None:
return True
else:
return compare(root.left, root.right)