from collections import deque
class BiTNode:
def __init__(self):
self.data = None
self.lchild = None
self.rchild = None
def arraytotree(arr, start, end):
if end >= start:
root = BiTNode()
mid = (end + start + 1)//2
root.data = arr[mid]
root.lchild = arraytotree(arr, start, mid-1)
root.rchild = arraytotree(arr, mid+1, end)
else:
return None
return root
def printTreeLayer(root):
if root == None:
return
queue = deque()
queue.append(root)
while len(queue)>0 :
p = queue.popleft()
print(p.data,end=' ')
if p.lchild != None:
queue.append(p.lchild)
if p.rchild != None:
queue.append(p.rchild)
if __name__ == '__main__':
arr = [i for i in range(1, 11)]
root = arraytotree(arr, 0, len(arr)-1)
print('树的层序遍历结果为:',end='')
printTreeLayer(root)
Python:如何从顶部开始逐层打印二叉树节点数据
最新推荐文章于 2021-08-30 23:17:03 发布