递归方式
一边用前序遍历,另一边则用后序遍历
将两边的遍历结果用列表存储起来,叶子不存在则用0代替存储,避免列表比较的时候误判
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param pRoot TreeNode类 # @return bool布尔型 # class Solution: def isSymmetrical(self , pRoot: TreeNode) -> bool: # write code here if not pRoot: return True lStack = [] rStack = [] lStack = self.qBianli(pRoot.left, lStack) rStack = self.hBianli(pRoot.right, rStack) if lStack == rStack: return True else: return False # 前序遍历 左 def qBianli(self, pRoot: TreeNode, lStack:list): if pRoot: self.qBianli(pRoot.left, lStack) self.qBianli(pRoot.right, lStack) lStack.append(pRoot.val) else: lStack.append(0) return lStack def hBianli(self, pRoot: TreeNode, rStack:list): if pRoot: self.hBianli(pRoot.right, rStack) self.hBianli(pRoot.left, rStack) rStack.append(pRoot.val) else: rStack.append(0) return rStack