[easy+][Tree] 101.Symmetric Tree
2017-11-08 本文已影响0人
小双2510
原题是:
Screen Shot 2017-11-07 at 1.54.16 PM.png思路是:
将给定的整颗树,进行复制。对复制的树,进行左右翻转操作,再对比翻转好的树,和原先的树是否是一样的树。
这里要注意的是,我犯过一个错误,将原先的树翻转之后,丢失原先的树了。所以增加了一个迭代函数对原先的树进行拷贝。
代码是:
# 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):
# deep copy tree root
def reverse(self,root):
if root == None:
return root
else:
tmp = root.left
root.left = root.right
root.right = tmp
root.left = self.reverse(root.left)
root.right = self.reverse(root.right)
return root
def isSame(self,root1,root2):
if root1 == None and root2 == None:
return True
elif not (root1 and root2):
return False
#elif not (root1.left or root1.right or root2.left or root2.right) and root1.val == root2.val:
# return True
elif root1.val != root2.val:
return False
return self.isSame(root1.left,root2.left) and self.isSame(root1.right,root2.right)
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
root = copy.deepcopy(root)
root_reverse = self.reverse(root_reverse)
return self.isSame(root,root_reverse)