参考了评论区大佬思路:
1.通过while语句遍历树
2.使用enumerate 实现之字形打印
# -*- 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 []
nodestack = [pRoot]
result = []
while nodestack:
res = []
nextstack = []
for i in nodestack:
res.append(i.val)
if i.left:
nextstack.append(i.left)
if i.right:
nextstack.append(i.right)
nodestack = nextstack
result.append(res)
returnRes = []
for idx,v in enumerate(result):
if idx%2==0:
returnRes.append(v)
else:
returnRes.append(v[::-1])
return returnRes 
京公网安备 11010502036488号