二叉树层次遍历下到上,左到右python
Posted limingqi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树层次遍历下到上,左到右python相关的知识,希望对你有一定的参考价值。
# 利用队列进行层次遍历就行
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的主要内容,如果未能解决你的问题,请参考以下文章