请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
可以与层序遍历二叉树类比。
这里需要使用两个栈,一个存放奇数行,一个存放偶数行。
# -*- 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 not pRoot:
return []
stack = [[], []]
current = 0
array = []
stack[current].append(pRoot)
temp = []
while stack[0] or stack[1]:
p = stack[current][-1]
temp.append(p.val)
if not current:
if p.left:
stack[1 - current].append(p.left)
if p.right:
stack[1 - current].append(p.right)
else:
if p.right:
stack[1 - current].append(p.right)
if p.left:
stack[1 - current].append(p.left)
stack[current].pop()
if not stack[current]:
current = 1 - current
array.append(temp)
temp = []
return array