题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
python实现:
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 按层打印,使用队列
def Print2(self, pRoot):
# write code here
if pRoot is None:
return []
result = []
tmpResult = []
from collections import deque
queue = deque([pRoot])
curLevelNum = 1
isEven = False
while queue:
while curLevelNum:
front = queue.popleft()
curLevelNum -= 1
tmpResult.append(front.val)
if front.left:
queue.append(front.left)
if front.right:
queue.append(front.right)
curLevelNum = len(queue)
if isEven:
result.append(tmpResult[::-1])
isEven = False
else:
result.append(tmpResult[:])
isEven = True
tmpResult = []
return result
# 法2:使用2个栈(剑指书上的思路)
def Print(self, pRoot):
# write code here
if pRoot is None:
return []
stack1, stack2 = [pRoot], []
result = []
tmp = []
from_left_to_right = True
while stack1 or stack2:
if stack1:
while stack1:
top = stack1.pop()
tmp.append(top.val)
if top.left:
stack2.append(top.left)
if top.right:
stack2.append(top.right)
# 此时stack1为空
result.append(tmp[:])
tmp = []
elif stack2:
while stack2:
top = stack2.pop()
tmp.append(top.val)
if top.right:
stack1.append(top.right)
if top.left:
stack1.append(top.left)
# 此时stack1为空
result.append(tmp[:])
tmp = []
return result