1 #!/usr/bin/python 2 # -*- coding: UTF-8 -*- 3 # added by kangye, dependent on python27 4 5 class BTree: 6 def __init__(self,value): 7 self.left=None 8 self.data=value 9 self.right=None 10 11 def insertLeft(self,value): 12 self.left=BTree(value) 13 return self.left 14 15 def insertRight(self,value): 16 self.right=BTree(value) 17 return self.right 18 19 def show(self): 20 print self.data 21 22 23 def inorder(node): 24 if node.data: 25 if node.left: 26 inorder(node.left) 27 node.show() 28 if node.right: 29 inorder(node.right) 30 31 32 def rinorder(node): 33 if node.data: 34 if node.right: 35 rinorder(node.right) 36 node.show() 37 if node.left: 38 rinorder(node.left) 39 40 def insert(node,value): 41 if value > node.data: 42 if node.right: 43 insert(node.right,value) 44 else: 45 node.insertRight(value) 46 else: 47 if node.left: 48 insert(node.left,value) 49 else: 50 node.insertLeft(value) 51 52 53 if __name__ == "__main__": 54 55 l=[88,11,2,33,22,4,55,33,221,34] 56 Root=BTree(l[0]) 57 node=Root 58 for i in range(1,len(l)): 59 insert(Root,l[i]) 60 61 print "1---->10" 62 inorder(Root) 63 print "10--->1" 64 rinorder(Root) 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
时间: 2024-11-10 05:23:21