在python中逐级打印二叉树 [英] print binary tree level by level in python
问题描述
我想以下列方式打印我的二叉树:
I want to print my binary tree in the following manner:
10
6 12
5 7 11 13
我已经编写了用于插入节点的代码,但无法编写用于打印树的代码.所以请帮忙解决这个问题.我的代码是:
I have written code for insertion of nodes but can't able to write for printing the tree. so please help on this . My code is :
class Node:
def __init__(self,data):
self.data=data
self.left=None
self.right=None
self.parent=None
class binarytree:
def __init__(self):
self.root=None
self.size=0
def insert(self,data):
if self.root==None:
self.root=Node(data)
else:
current=self.root
while 1:
if data < current.data:
if current.left:
current=current.left
else:
new=Node(data)
current.left=new
break;
elif data > current.data:
if current.right:
current=current.right
else:
new=Node(data)
current.right=new
break;
else:
break
b=binarytree()
推荐答案
您正在寻找的是 breadth-first traversal,它可以让您逐层遍历树.基本上,你使用一个队列来跟踪你需要访问的节点,在你去的时候将子节点添加到队列的后(而不是将它们添加到前> 堆栈).先开始工作.
What you're looking for is breadth-first traversal, which lets you traverse a tree level by level. Basically, you use a queue to keep track of the nodes you need to visit, adding children to the back of the queue as you go (as opposed to adding them to the front of a stack). Get that working first.
这样做之后,您就可以计算出树有多少层(log2(node_count) + 1
)并使用它来估计空白.如果您想获得完全正确的空格,您可以使用其他数据结构来跟踪每个级别需要多少空格.不过,使用节点数和级别数进行智能估计就足够了.
After you do that, then you can figure out how many levels the tree has (log2(node_count) + 1
) and use that to estimate whitespace. If you want to get the whitespace exactly right, you can use other data structures to keep track of how many spaces you need per level. A smart estimation using number of nodes and levels should be enough, though.
这篇关于在python中逐级打印二叉树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!