这题判断一棵树是否是对称的。我用的是中序和后序2次来看结果。代码如下:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root == None:
return True
if root.left == None and root.right == None:
return True
a = []
b = []
e = []
def left(root):
if root.left != None:
left(root.left)
a.append(root.val)
if root.right != None:
left(root.right)
left(root)
if a[:len(a) / 2] == a[len(a) / 2 + 1:][::-1]:
c = True
else:
c = False
def left1(root):
if root.left != None:
left1(root.left)
if root.right != None:
left1(root.right)
b.append(root.val)
left1(root)
def right1(root):
if root.right != None:
right1(root.right)
if root.left != None:
right1(root.left)
e.append(root.val)
right1(root)
if b == e:
d = True
else:
d = False
return c and d