Q:
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3]
是对称的。
1 / \ 2 2 / \ / \ 3 4 4 3
但是下面这个 [1,2,2,null,3,null,3]
则不是镜像对称的:
1 / \ 2 2 \ \ 3 3
链接:https://leetcode-cn.com/problems/symmetric-tree/description/
思路:使用中序遍历,然后判断输出是否是回文串
代码:
# 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):
"""
:type root: TreeNode
:rtype: bool
"""
if root == None:
return True
else:
res = []
self.middle_digui(root, res)
print (res)
if res == res[::-1]:
return True
else:
return False
def middle_digui(self,root,res):
if root == None:
return
if root.left and not root.right:
res.append(None)
self.middle_digui(root.left,res)
res.append(root.val)
self.middle_digui(root.right,res)
if root.right and not root.left:
res.append(None)