天天看點

Python簡單前序建立二叉樹及二叉樹的周遊

一、學習要點:

1.python中不能用結構體,C和C++實作二叉樹多用結構體,python中隻用對象;

二、代碼實作:

class Tree():
	def __init__(self,data=-1,lchild=None,rchild=None):
		self.data=data
		self.lchild=lchild
		self.rchild=rchild
	def CreateTree(self):
		data=int(input("please input the data:"))
		if(data==-1):
			return
		else:
			self.data=data
			self.lchild=Tree()
			self.lchild.CreateTree()
			self.rchild.CreateTree()
	def preorder_print(self):
		if(self.data==-1):
			return
		else:
			print('%d'%(self.data))
			self.lchild.preorder_print()
			self.rchild.preorder_print()
           

三、運作結果

Python簡單前序建立二叉樹及二叉樹的周遊