需求
给你一个二叉树的根节点 root , 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3]
输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3]
输出:false
输出
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isSymmetric(root):
def checkSymmetry(left, right):
# 如果两个子树都为空,则对称
if not left and not right:
return True
# 如果一个子树为空,另一个不为空,则不对称
if not left or not right:
return False
# 当前节点值相等,并且左右子树分别对称
return (left.val == right.val) and checkSymmetry(left.left, right.right) and checkSymmetry(left.right,
right.left)
# 如果根节点为空,直接判断为对称
if not root:
return True
# 开始递归检查
return checkSymmetry(root.left, root.right)
# 示例测试
# 构建示例1的二叉树
# 1
# / \
# 2 2
# / \ / \
# 3 4 4 3
root1 = TreeNode(1, TreeNode(2, TreeNode(3), TreeNode(4)), TreeNode(2, TreeNode(4), TreeNode(3)))
print(isSymmetric(root1)) # 应输出 True
# 构建示例2的二叉树
# 1
# / \
# 2 2
# \ \
# 3 3
root2 = TreeNode(1, TreeNode(2, None, TreeNode(3)), TreeNode(2, None, TreeNode(3)))
print(isSymmetric(root2)) # 应输出 False