题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
解题思路
对二叉树进行层次遍历,然后在每一层放置一个标志,若当前层是偶数层,则将当前层遍历结果添加到result数组中,否则添加当前层遍历结果的反转数组。
完整代码
# -*- coding:utf-8 -*-
# import copy
# 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 []
i = 0
tree = []
tree.append(pRoot)
tree.append(1)
result = []
stack = []
while tree:
temp = tree[0]
tree.remove(temp)
if temp == 1:
if i % 2 == 0:
result.append(stack[0:])
else:
stack1 = stack[-1: 0: -1]
stack1.append(stack[0])
result.append(stack1)
stack = []
if len(tree) != 0:
i += 1
tree.append(1)
else:
stack.append(temp.val)
if temp.left:
tree.append(temp.left)
if temp.right:
tree.append(temp.right)
return result