我的思路为中序遍历和逆中序遍历的结果是相同的。这种思路是错的,原因在于
[1,2,2,2,null,2]这种情况下回出现错误。
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)
随后看了官方解答,进行了递归算法的实现。
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)
因为通过递归的方式可以实现,自然想到通过栈的方式(其实在这道题中用队列也可以实现)。
# 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