請實現一個函數,用來判斷一顆二叉樹是不是對稱的。注意,如果一個二叉樹同此二叉樹的鏡像是同樣的,定義其爲對稱的。
有兩種方法,一種是遞歸的:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetrical(self, pRoot):
if pRoot == None:
return True
return self.compare(pRoot.left, pRoot.right)
def compare(self, pRoot1, pRoot2):
if not pRoot1 and not pRoot2:
return True
if not pRoot1 or not pRoot2:
return False
if pRoot1.val == pRoot2.val:
if self.compare(pRoot1.left, pRoot2.right) :
if self.compare(pRoot1.right, pRoot2.left):
return True
return False
非遞歸方法:採用層序遍歷,查詢每一層是不是滿足對稱的關係
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetrical(self, pRoot):
if pRoot == None:
return True
s = []
s.append(pRoot.left)
s.append(pRoot.right)
while(len(s)!=0):
right = s.pop(-1)
left = s.pop(-1)
if not left and not right:
continue
if not left or not right:
return False
if left.val != right.val:
return False
s.append(left.left)
s.append(right.right)
s.append(left.right)
s.append(right.left)
return True