SHARE
TWEET

Untitled

a guest Jun 19th, 2019 55 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class BNode:
  2.  
  3.   def __init__(self, content, left=None, right=None):
  4.     self.content = content
  5.     self.left = left
  6.     self.right = right
  7.  
  8.   def __str__(self):
  9.     string = ""
  10.     if self.content is not None:
  11.       string += str(self.content)
  12.     if self.left is not None:
  13.       string += "L" + str(self.left)
  14.     if self.right is not None:
  15.       string += "R" + str(self.right)
  16.     return string
  17.  
  18.  
  19. class BTree:
  20.  
  21.   def __init__(self, root):
  22.     self.root = root
  23.  
  24.   def __str__(self):
  25.     return str(self.root) if self.root is not None else "<<E>>"
  26.  
  27.   def add(self, content):
  28.     new_node = BNode(content)
  29.     current_node = self.root
  30.     if self.root is None:
  31.       self.root = new_node
  32.       return
  33.     while current_node is not None:
  34.       if current_node.content > new_node.content:
  35.         if current_node.left is None:
  36.           current_node.left = new_node
  37.         else:
  38.           current_node = current_node.left
  39.       elif current_node.content < new_node.content:
  40.         if current_node.right is None:
  41.           current_node.right = new_node
  42.         else:
  43.           current_node = current_node.right
  44.       else:
  45.         break
  46.  
  47.   def find(self, content):
  48.     current_node = self.root
  49.     while current_node is not None:
  50.       if current_node.content == content:
  51.         return current_node
  52.       elif current_node.content < content:
  53.         current_node = current_node.right
  54.       else:
  55.         current_node = current_node.left
  56.     return None
  57.  
  58.   def add_many(self, array, min, max, root):
  59.     mid = int((min + max) / 2)
  60.     if min > max:
  61.       return
  62.     self.add(array[mid])
  63.     self.add_many(array, min, mid - 1, self.root.left)    
  64.     self.add_many(array, mid + 1, max, self.root.right)
  65.  
  66.  
  67.   def convert(self, array):
  68.     array = sorted(array)
  69.     self.root = None
  70.     self.add_many(array, 0, len(array) - 1, self.root)
  71.  
  72.    
  73.  
  74.  
  75.  
  76.  
  77. node_left =  BNode(5)
  78. node_right = BNode(15)
  79. node = BNode(10, node_left, node_right)
  80.  
  81. tree = BTree(node)
  82. tree.root = None
  83. arr = [6, 4, 8, 7, 9 ,1, 10]
  84. tree.convert(arr)
  85. print(tree)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top