题目描述:
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
# -*- 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 []
pl = [[pRoot]]
while pl[-1] != []:
t = []
for n in pl[-1]:
if n.left:
t.append(n.left)
if n.right:
t.append(n.right)
pl.append(t)
res = []
flag = 0
for l in pl[:-1]:
t = []
for n in l:
t.append(n.val)
if flag % 2 != 0:
t.reverse()
flag += 1
res.append(t)
return res