(Python 2.7)我需要打印一个二叉树的bfs,包含一个给定的前序和inorder,以及一个最大长度的前序和inorder序列。 我知道它是如何工作的,例如: 序:ABCDE 序:CBDAE 最大长度:5BFS in python from preorder and in
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中创建一个二叉树,但事情是我不知道如何添加下一个孩子的值。正如你所看到的,我已经有了根,并想出了如何插入第一个孩子(左侧和右侧),但我不知道如何添加下一个孩子。
像root.left_child。 setLeftChild(BinaryTree(preorder [2]))? – TomMe