题目:请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
牛客网:链接
二叉树的镜像和对称二叉树的区别:
源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5
对称二叉树
8
/ \
10 10
/ \ / \
11 9 9 11
代码:
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetrical(self, pRoot):
# write code here
if not pRoot:
return True
if not pRoot.left and not pRoot.right:
return True
return self.symmeric(pRoot.left, pRoot.right)
def symmeric(self, rootA, rootB):
if not rootA and not rootB:
return True
if not rootA or not rootB or rootA.val != rootB.val:
return False
return self.symmeric(rootA.left, rootB.right) and self.symmeric(rootA.right, rootB.left)
pNode1 = TreeNode(8)
pNode2 = TreeNode(6)
pNode1.left = pNode2
S = Solution()
result = S.isSymmetrical(pNode1)
print(result)