1 2 4 0 0 5 0 0 3 0 6 0 0
这是先序输入,0则代表空节点,也就是None
PrintTree1,2,3,4分别代表先序中序后序层序输出
1,2,3没问题,层序报错出了问题,但是结果最终还是出来了
class Tree():
def __init__(self):
self.data='0'
self.lchild=None
self.rchild=None
self.myQueue=[]
def Create(self,list):
data=list[0]
del list[0]
if data=='0':
return
else:
self.data=data
self.lchild=Tree()
self.lchild.Create(list)
self.rchild=Tree()
self.rchild.Create(list)
def PrintTree(self):#输出树
if self.data=='0':
return
else:
print(int(self.data),end=' ')
self.lchild.PrintTree()
self.rchild.PrintTree()
def PrintTree2(self):
if self.data=='0':
return
else:
self.lchild.PrintTree2()
print(int(self.data), end=' ')
self.rchild.PrintTree2()
def PrintTree3(self):
if self.data=='0':
return
else:
self.lchild.PrintTree3()
self.rchild.PrintTree3()
print(int(self.data), end=' ')
def PrintTree4(self):
if self.rchild.data=='0' and self.lchild.data=='0':
return
myQueue=[]
node=self
myQueue.append(self)
while myQueue:
node=myQueue[0]
myQueue.pop(0)
if node.data!='0':
print(node,end=' ')
if node.lchild!='0':
myQueue.append(node.data.lchild)
if node.rchild!='0':
myQueue.append(node.rchild)
list = input()
list = list.split(' ')
a = Tree()
a.Create(list)
a.PrintTree()
print()
a.PrintTree2()
print()
a.PrintTree3()
print()
a.PrintTree4()
有人帮忙看看嘛,就这一个报错,但是最终结果还是出来了