一、节点类的定义
class Node():
def __init__(self, data, left, right):
self.data = data
self.left = left
self.right = right
二、生成二叉树
class BTree:
def __init__(self):
self.root = None
def insert(self, data): #插入节点
r = self.root
if r is None:
self.root = Node(data, None, None)
return
while True:
# 比根结点小放在左边
if r.data > data:
if r.left is None:
r.left = Node(data, None, None)
break
else:
r = r.left
else:
# 比根结点大放在右边
if r.right is None:
r.right = Node(data, None, None)
break
else:
r = r.right
三、前序遍历
def preoder(self, root):
if root is None:
return
else:
print root.data
self.preoder(root.left)
self.preoder(root.right)
四、中序遍历
def midoder(self, root):
if root is None:
return
else:
self.midoder(root.left)
print root.data
self.midoder(root.right)
五、后序遍历
def postoder(self, root):
if root is None:
return
else:
self.postoder(root.left)
self.postoder(root.right)
print root.data
六、测试
if __name__ == '__main__':
bt = BTree()
L=[3,7,5,8,9,10,11,2,6,4]
for i in L:
bt.insert(i)
bt.preoder(bt.root)
bt.midoder(bt.root)
bt.postoder(bt.root)
七、总代吗
class Node():
def __init__(self,root):
self.root=root
self.lchild=None
self.rchild=None
class Bitree():
def __init__(self):
self.root=None
def insert(self,root,node): #插入节点
if root:
if root.root>node.root:
if root.lchild:
self.insert(root.lchild,node)
else:
root.lchild=node
else:
if root.rchild:
self.insert(root.rchild,node)
else:
root.rchild=node
else:
return 0
def initBitree(self,data): #生成二叉树
root=Node(data[0])
length=len(data)
for x in range(1,length):
node=Node(data[x])
self.insert(root,node)
return root
def preoder(self,root): #先序遍历
if root:
print(root.root)
self.preoder(root.lchild)
self.preoder(root.rchild)
def midoder(self,root): #中序遍历
if root:
self.midoder(root.lchild)
print(root.root)
self.midoder(root.rchild)
def postoder(self,root): #后序遍历
if root:
self.postoder(root.lchild)
self.postoder(root.rchild)
print(root.root)
if __name__ == '__main__':
data=[3,7,5,8,9,10,11,2,6,4]
Bitree=Bitree()
a=Bitree.initBitree(data)
print('前序遍历:')
Bitree.preoder(a)
print('中序遍历:')
Bitree.midoder(a)
print('后序遍历:')
Bitree.postoder(a)