题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。1 # -*- coding:utf-8 -*- 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 class Solution: 8 def Print(self, pRoot): 9 # write code here 10 if pRoot == None: 11 return [] 12 stack1=[pRoot] 13 stack2=[] 14 ret=[] 15 while stack1 or stack2: 16 if stack1: 17 tmpRet = [] 18 while stack1: 19 tmpNode = stack1.pop() 20 tmpRet.append(tmpNode.val) 21 if tmpNode.left: 22 stack2.append(tmpNode.left) 23 if tmpNode.right: 24 stack2.append(tmpNode.right) 25 ret.append(tmpRet) 26 if stack2: 27 tmpRet=[] 28 while stack2: 29 tmpNode = stack2.pop() 30 tmpRet.append(tmpNode.val) 31 if tmpNode.right: 32 stack1.append(tmpNode.right) 33 if tmpNode.left: 34 stack1.append(tmpNode.left) 35 ret.append(tmpRet) 36 return ret
2020-01-01 17:39:12