Iterative solution:
# Iterative Solution
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a boolean
def isSymmetric(self, root):
if root==None:
return True
else:
Ninlvl=[root.left, root.right]
while Ninlvl!=[None]*len(Ninlvl):
n=len(Ninlvl)
if n%2!=0:
return False
for i in range(n):
if Ninlvl[i]==None and Ninlvl[n-i-1]!=None:
return False
ndVs=[i.val for i in Ninlvl if i]
m=len(ndVs)
if ndVs[0:int(m/2)]!=ndVs[:int(m/2)-1:-1]:
return False
NextNinlvl=[]
for i in Ninlvl:
if i:
NextNinlvl+=[i.left,i.right]
Ninlvl=NextNinlvl
return True
Recursive Solution:
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a boolean
def smtc(self,T1,T2):
if T1==T2==None:
return True
elif not T1 or not T2:
return False
elif T1.val==T2.val:
return True if self.smtc(T1.left,T2.right) and self.smtc(T1.right,T2.left) else False
else:
return False
def isSymmetric(self, root):
if not root:
return True
return self.smtc(root.left,root.right)
No comments :
Post a Comment