import Queue
class node(object):
def __init__(self,data=None,left=None,right=None):
self.data=data
self.left=left
self.right=right
def print_by_layer(tree):
if not tree:
return
q = Queue.Queue()
q.put(tree)
while not q.empty():
size = q.qsize()
for i in range(size):
t = q.get()
print t.data,
if t.left:
q.put(t.left)
if t.right:
q.put(t.right)
print ""
if __name__=='__main__':
tree=node('D',node('B',node('A'),node('C')),node('E',right=node('G',node('F'))))
print_by_layer(tree)二叉树的水平(层次)遍历 -- Python
最新推荐文章于 2021-12-07 21:52:34 发布
本文介绍了一种使用队列实现的二叉树层序遍历算法,并提供了一个具体的Python实现示例。该算法首先将根节点放入队列中,然后逐层遍历每个节点并打印其数据。
363

被折叠的 条评论
为什么被折叠?



