题目描述:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
思路1:
递归的思路是如果一棵树为镜像树,那么它的左右子树也一定为镜像树,且根节点的右子树和左子树相同。
递归AC代码:
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def isMirror(root1, root2):
if not root1 and not root2:
return True
if not root1 or not root2:
return False
return (root1.val == root2.val) and isMirror(root1.left, root2.right) and isMirror(root1.right, root2.left)
return isMirror(root, root)
思路2:
对该树进行逆转,通过对前后二次树均进行前序和中序遍历(因为前序遍历加中序遍历能够唯一确定一棵树),看两个结果是否相同来判断是否为镜像树。
AC代码:
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
ans = []
def inOrderTravel(root):
if root.left:
inOrderTravel(root.left)
ans.append(root.val)
if root.right:
inOrderTravel(root.right)
def preOrderTravel(root):
ans.append(root.val)
if root.left:
preOrderTravel(root.left)
if root.right:
preOrderTravel(root.right)
def invert(root):
temp = root.left
root.left = root.right
root.right = temp
if root.left:
invert(root.left)
if root.right:
invert(root.right)
inOrderTravel(root)
preOrderTravel(root)
invert(root)
inOrderTravel(root)
preOrderTravel(root)
if ans[:len(ans) // 2] == ans[len(ans) // 2:]:
return True
else:
return False