Advertisement
regzarr

ADA_l2x1

Mar 1st, 2023
534
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.05 KB | None | 0 0
  1. class Node:
  2.     def __init__(self, val):
  3.         self.l_child = None
  4.         self.r_child = None
  5.         self.parent = None
  6.         self.data = val
  7.        
  8.     def __repr__(self):
  9.         if hasattr(self, 'data'):
  10.             return str(self.data)
  11.         return "N/A, does not exist"
  12.        
  13.     def __str__(self):
  14.         return "\t  " + str(self.data) + "\n\t / \\\n\t" + str(self.l_child.data) + "   " + str(self.r_child.data)
  15.  
  16. def binary_insert(root, node):
  17.     if root is None:
  18.         root = node
  19.     else:
  20.         if root.data > node.data: # insert on left side
  21.             if root.l_child is None:
  22.                 root.l_child = node
  23.             else:
  24.                 binary_insert(root.l_child, node)
  25.         else: # insert on right side
  26.             if root.r_child is None:
  27.                 root.r_child = node
  28.             else:
  29.                 binary_insert(root.r_child, node)
  30.  
  31. def in_order_print(root):
  32.     if not root:
  33.         return
  34.     in_order_print(root.l_child)
  35.     print(root.data)
  36.     in_order_print(root.r_child)
  37.  
  38. def pre_order_print(root):
  39.     if not root:
  40.         return        
  41.     print(root.data)
  42.     pre_order_print(root.l_child)
  43.     pre_order_print(root.r_child)    
  44.    
  45. def height(root, h = 0):
  46.     if not root:
  47.         return h
  48.     leftHeight = height(root.l_child, h + 1)
  49.     rightHeight = height(root.r_child, h + 1)
  50.     return max(leftHeight, rightHeight)
  51.  
  52. def search(root, key):
  53.     if (root.data == key):
  54.         return root
  55.     if not root:
  56.         return
  57.     if (key < root.data):
  58.         return search(root.l_child, key)
  59.     else:
  60.         return search(root.r_child, key)
  61.        
  62. def successor(root):
  63.     if not root:
  64.         return
  65.     #print(root)
  66.     if(root.r_child is None):
  67.         return None
  68.     successor = root.r_child
  69.    
  70.     while(successor.l_child):
  71.         successor = successor.l_child
  72.    
  73.     return successor.data
  74.  
  75. root = Node(5)
  76. binary_insert(root, Node(3))
  77. binary_insert(root, Node(8))
  78. binary_insert(root, Node(1))
  79. in_order_print(root)
  80. print(successor(root))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement