halaluddin

Top View

Sep 19th, 2019
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.13 KB | None | 0 0
  1. class Node:
  2.     def __init__(self, info):
  3.         self.info = info  
  4.         self.left = None  
  5.         self.right = None
  6.         self.level = None
  7.  
  8.     def __str__(self):
  9.         return str(self.info)
  10.  
  11. class BinarySearchTree:
  12.     def __init__(self):
  13.         self.root = None
  14.  
  15.     def create(self, val):  
  16.         if self.root == None:
  17.             self.root = Node(val)
  18.         else:
  19.             current = self.root
  20.          
  21.             while True:
  22.                 if val < current.info:
  23.                     if current.left:
  24.                         current = current.left
  25.                     else:
  26.                         current.left = Node(val)
  27.                         break
  28.                 elif val > current.info:
  29.                     if current.right:
  30.                         current = current.right
  31.                     else:
  32.                         current.right = Node(val)
  33.                         break
  34.                 else:
  35.                     break
  36.  
  37. def findMaxMin(root, max, min, hd = 0):
  38.     if root is None:
  39.         return
  40.  
  41.     if hd < min[0]:
  42.         min[0] = hd
  43.     elif hd > max[0]:
  44.         max[0] = hd
  45.  
  46.     findMaxMin(root.left, max, min, hd-1)
  47.     findMaxMin(root.right, max, min, hd+1)
  48.  
  49. def VerticalTree(root, node_no, node_dict, hd=0):
  50.     if root is None:return
  51.  
  52.     if node_no == hd:
  53.         node_dict[node_no].append(root.info)
  54.  
  55.     VerticalTree(root.left, node_no, node_dict, hd-1)
  56.     VerticalTree(root.right, node_no, node_dict, hd+1)
  57.  
  58. def printTopView(node_dict, max, min):
  59.     for line_no in range(min[0], max[0]+1):
  60.         print(node_dict[line_no][0], end=' ')
  61.  
  62. def topView(root):
  63.     max, min = [0], [0]
  64.     findMaxMin(root, max, min)
  65.     node_dict = {}
  66.     for node_no in range(min[0], max[0]+1):
  67.         node_dict[node_no] = []
  68.  
  69.     for node_no in range(min[0], max[0]+1):
  70.         VerticalTree(root, node_no, node_dict)
  71.  
  72.     printTopView(node_dict, max, min)
  73.  
  74.  
  75. if __name__ == "__main__":
  76.     tree = BinarySearchTree()
  77.     t = int(input())
  78.  
  79.     arr = list(map(int, input().split()))
  80.  
  81.     for i in range(t):
  82.         tree.create(arr[i])
  83.  
  84.     topView(tree.root)
Add Comment
Please, Sign In to add comment