我的思路為中序遍歷和逆中序遍歷的結(jié)果是相同的。這種思路是錯(cuò)的,原因在于
[1,2,2,2,null,2]這種情況下回出現(xiàn)錯(cuò)誤。
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
queue1 = []
queue2 = []
self.Inorder(root,queue1)
self.inverseInorder(root, queue2)
if queue1 == queue2:
return True
else:
return False
def Inorder(self, root,queue):
if root is None:
return
self.Inorder(root.left,queue)
queue.append(root.val)
self.Inorder(root.right,queue)
def inverseInorder(self, root,queue):
if root is None:
return
self.inverseInorder(root.right,queue)
queue.append(root.val)
self.inverseInorder(root.left,queue)
隨后看了官方解答,進(jìn)行了遞歸算法的實(shí)現(xiàn)。
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
return self.isMirror(root,root)
def isMirror(self, rootleft, rootright):
if rootleft == None and rootright == None:
return True
if rootleft == None or rootright == None:
return False
if rootleft.val != rootright.val:
return False
return self.isMirror(rootleft.left, rootright.right) and self.isMirror(rootleft.right, rootright.left)
因?yàn)橥ㄟ^遞歸的方式可以實(shí)現(xiàn),自然想到通過棧的方式(其實(shí)在這道題中用隊(duì)列也可以實(shí)現(xiàn))。
# 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: TreeNode) -> bool:
if not root:
return True
stack = [root.left,root.right]
while stack:
t1 = stack.pop()
t2 = stack.pop()
if (not t1 and not t2):
continue
if(not t1 or not t2):
return False
if (t1.val != t2.val):
return False
stack.append(t1.left)
stack.append(t2.right)
stack.append(t1.right)
stack.append(t2.left)
return True