#! /usr/bin/python
#-*- coding:cp936 -*-
class Node:
def __init__(self,value = None):
self.left = None
self.right = None
self.data = value
class BinaryTree(Node):
def __init__(self,value):
self.root = Node.__init__(self, value)
def Insert(self,value):
self.InsertHelper(value, self)
def InsertHelper(self,value,_root):
if value > _root.data:
if _root.right == None:
_root.right = Node(value)
return
else:
self.InsertHelper(value,_root.right)
return
elif value < _root.data:
if _root.left == None:
_root.left = Node(value)
else:
self.InsertHelper(value, _root.left)
else:
return
def Traversal(self,select):
if select == 1:
self.TraversalPre(self)
elif select ==2:
self.TraversalNext(self)
pass
elif select ==3:
self.TraversalEnd(self)
pass
else:
raise ("dup")
def TraversalPre(self,_root):
if _root is not None:
print _root.data
self.TraversalPre(_root.left)
self.TraversalPre(_root.right)
def TraversalNext(self,_root):
if _root is not None:
self.TraversalNext(_root.left)
print _root.data
self.TraversalNext(_root.right)
def TraversalEnd(self,_root):
if _root is not None:
self.TraversalEnd(_root.left)
self.TraversalEnd(_root.right)
print _root.data
if __name__ == '__main__':
x = BinaryTree(100)
for i in range(200,205):
x.Insert(i)
for i in range(100,80,-5):
x.Insert(i)
x.Traversal(1)
x.Traversal(2)
x.Traversal(3)
|