Idea: conventional prior order traversal, the order is root-left-right.
We follow the order and define a prior order traversal-β method, whose order is root-right-left.
Assuming a tree is a symmetric binary tree, then conventional order The traversal results of the traversal method and the pre-order traversal-β method should be the same.
Ontology adopts this idea to compare the above two traversal results of a tree.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.leftlist = []
self.rightlist = []
def isSymmetric(self, root: TreeNode) -> bool:
if root is None:
return True
elif root.left is None and root.right is None:
return True
elif root.left is None or root.right is None:
return False
self.root_left_right(root)
self.root_right_left(root)
return True if self.leftlist == self.rightlist else False
def root_left_right(self,node):#常规先序遍历
if node is None:
self.leftlist.append('x')
else:
self.leftlist.append(node.val)
self.root_left_right(node.left)
self.root_left_right(node.right)
def root_right_left(self,node):#先序-beta
if node is None:
self.rightlist.append('x')
else:
self.rightlist.append(node.val)
self.root_right_left(node.right)
self.root_right_left(node.left)