Package miopia :: Package util :: Module BinaryTree
[hide private]
[frames] | no frames]

Source Code for Module miopia.util.BinaryTree

  1  ''' 
  2  Created on 14/06/2013 
  3   
  4  @author: david.vilares 
  5  ''' 
  6   
  7   
8 -class Node:
9
10 - def __init__(self, key, data):
11 # initializes the data members 12 self.left = None 13 self.right = None 14 self.data = data 15 self.key = key
16
17 -class BinaryTree:
18 - def __init__(self):
19 # initializes the root member 20 self.root = None
21
22 - def addNode(self, key,data):
23 # creates a new node and returns it 24 return Node(key,data)
25
26 - def insert(self, root, key, data):
27 # inserts a new data 28 if root == None: 29 # it there isn't any data 30 # adds it and returns 31 self.root = self.addNode(key,data) 32 return self.addNode(key,data) 33 else: 34 # enters into the tree 35 if key <= root.key: 36 # if the data is less than the stored one 37 # goes into the left-sub-tree 38 root.left = self.insert(root.left, key,data) 39 else: 40 # processes the right-sub-tree 41 root.right = self.insert(root.right, key,data) 42 return root
43
44 - def printTree(self, root):
45 # prints the tree path 46 if root == None: 47 pass 48 else: 49 self.printTree(root.left) 50 print root.key, 51 self.printTree(root.right)
52 53
54 - def lookup(self, root, target):
55 # looks for a value into the tree 56 if root == None: 57 return 0 58 else: 59 # if it has found it... 60 if target == root.key: 61 return 1 62 else: 63 if target < root.key: 64 # left side 65 return self.lookup(root.left, target) 66 else: 67 # right side 68 return self.lookup(root.right, target)
69 70
71 - def search_longest_match(self,root,target):
72 if root == None: 73 return None 74 if target.startswith(root.key): 75 if target < root.key: 76 #print "Entra", target, root.key, root.data 77 return self.search_longest_match(root.right, target) 78 else: 79 return root.data 80 else: 81 if target < root.key: 82 return self.search_longest_match(root.left,target) 83 else: 84 return self.search_longest_match(root.right, target)
85 86 87 ## create the binary tree 88 #BTree = BinaryTree() 89 # # add the root node 90 #root = BTree.addNode('administrador',[1,2]) 91 # # ask the user to insert values 92 # 93 # 94 #n1 = Node('aa',[3,4]) 95 #n2 = Node('pa',[4,5]) 96 # 97 #for i in [n1,n2]: # insert values 98 # print BTree.insert(root, i.key,i.data) 99 # 100 #BTree.printTree(root) 101