59.按之字形顺序打印二叉树(python)
题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def Print(self, pRoot): # write code here if pRoot == None: return [] stack1=[pRoot] stack2=[] ret=[] while stack1 or stack2: if stack1: tmpRet = [] while stack1: tmpNode = stack1.pop() tmpRet.append(tmpNode.val) if tmpNode.left: stack2.append(tmpNode.left) if tmpNode.right: stack2.append(tmpNode.right) ret.append(tmpRet) if stack2: tmpRet=[] while stack2: tmpNode = stack2.pop() tmpRet.append(tmpNode.val) if tmpNode.right: stack1.append(tmpNode.right) if tmpNode.left: stack1.append(tmpNode.left) ret.append(tmpRet) return ret
2020-01-01 17:39:12
相关推荐
夜斗不是神 2020-11-17
huavhuahua 2020-11-20
Yasin 2020-11-16
xiaoseyihe 2020-11-16
千锋 2020-11-15
diyanpython 2020-11-12
chunjiekid 2020-11-10
wordmhg 2020-11-06
世事一场大梦 2020-11-17
xiaoseyihe 2020-11-16
Morelia 2020-11-03
CloudXli 2020-11-03
文山羊 2020-10-31
comtop0 2020-10-31
pythonxuexi 2020-10-30
三石 2020-10-29
chaochao 2020-10-27
PythonMaker 2020-10-27