python 二叉树
#coding:utf-8__author__ = 'similarface'
class BinaryTree:
def __init__(self):
self.tree=EmptyNode()
def __repr__(self):
return repr(self.tree)
def lookup(self, value):
return self.tree.lookup(value)
def insert(self, value):
self.tree = self.tree.insert(value)
class EmptyNode:
def __repr__(self):
return '*'
#叶子节点返回false
def lookup(self,value):
return False
#树的低端添加新节点
def insert(self,value):
return BinaryNode(self,value,self)
class BinaryNode:
def __init__(self,left,value,right):
print(left,value,right)
self.data, self.left, self.right = value,left,right
def lookup(self,value):
if self.data==value:
return True
elif self.data>value:
return self.left.lookup(value)
else:
return self.right.lookup(value)
def insert(self,value):
if self.data>value:
self.left=self.left.insert(value)
elif self.data<value:
self.right=self.right.insert(value)
return self
def __repr__(self):
return ('( %s, %s, %s )' % (repr(self.left), repr(self.data), repr(self.right)))
if __name__=="__main__":
x=BinaryTree()
for i in [3,1,2]:
x.insert(i)
for i in range(8):
print((i,x.lookup(i)))
print('---------------------')
y=BinaryTree()
for i in [3,1,9,2,7]:
y.insert(i)
print(y)
print('----------z-----------')
z=BinaryTree()
for c in 'badce':
z.insert(c)
print(z)
以上是 python 二叉树 的全部内容, 来源链接: utcz.com/z/388501.html