(Python 2.7)我需要打印出给定先序和中序的二叉树的广度优先遍历,并且先序和中序字符串的最大长度已知。
我知道它是如何工作的,例如:
先序:ABCDE
中序:CBDAE
最大长度:5
A
/ \
B E
/ \
C D
BFS:ABECD
到目前为止,我已经理解了这个内容。
class BinaryTree:
def __init__ (self, value, parent=None):
self.parent = parent
self.left_child = None
self.right_child = None
self.value=value
def setLeftChild(self, child=None):
self.left_child = child
if child:
child.parent = self
def setRightChild(self, child=None):
self.right_child = child
if child:
child.parent = self
preorder={}
inorder={}
print "max string length?"
i=int(raw_input())
count=0
while i>count:
print"insert the preorder"
preorder[raw_input()]=count
count=count+1
print "preorder is",sorted(preorder, key=preorder.get)
count2=0
while i>count2:
print"insert the inorder"
inorder[raw_input()]=count2
count2=count2+1
print "inorder is",sorted(inorder, key=inorder.get)
root=
我已经学会了如何在Python中创建二叉树,但是问题是我不知道如何添加下一个子节点的值。正如您所看到的,我已经有了根节点,并且学会了如何插入第一个子节点(左和右),但我不知道如何添加下一个子节点。