码迷,mamicode.com
首页 > 编程语言 > 详细

二叉树层次遍历下到上,左到右python

时间:2020-03-12 11:33:42      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:end   one   for   none   res   init   return   poi   层次遍历   

# 利用队列进行层次遍历就行
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:

def Print(self, pRoot):

if not pRoot:
return []
queue = [pRoot]
outList = []
while queue:
res = []
nextQueue = []
for point in queue: # 这里再遍历每一层
res.append(point.val)
if point.left:
nextQueue.append(point.left)
if point.right:
nextQueue.append(point.right)
outList.append(res)
queue = nextQueue #覆盖的作用
return outList[::-1]


t = TreeNode(0)
t.left = TreeNode(1)
t.right = TreeNode(2)
t.left.left = TreeNode(3)
t.left.right = TreeNode(6)
t.right.left = TreeNode(7)

s=Solution()
print(s.Print(t))

二叉树层次遍历下到上,左到右python

标签:end   one   for   none   res   init   return   poi   层次遍历   

原文地址:https://www.cnblogs.com/limingqi/p/12467847.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!