|
| 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 | +""" |
| 38 | +Node is defined as |
| 39 | +self.left (the left child of the node) |
| 40 | +self.right (the right child of the node) |
| 41 | +self.info (the value of the node) |
| 42 | +""" |
| 43 | +def topView(root): |
| 44 | + #Write your code here |
| 45 | + # Using Level Order Traversal |
| 46 | + dic, queue, current, current.level = dict(), [], root, 0 |
| 47 | + queue.append(current) |
| 48 | + while len(queue)>0: |
| 49 | + current = queue.pop(0) |
| 50 | + try: |
| 51 | + dic[current.level].append(current.info) |
| 52 | + except: |
| 53 | + dic[current.level] = [current.info] |
| 54 | + if current.left: |
| 55 | + queue.append(current.left) |
| 56 | + current.left.level = current.level-1 |
| 57 | + if current.right: |
| 58 | + queue.append(current.right) |
| 59 | + current.right.level = current.level+1 |
| 60 | + for i in sorted(dic): |
| 61 | + print(dic[i][0], end = ' ') |
| 62 | + |
| 63 | + |
| 64 | + |
| 65 | +tree = BinarySearchTree() |
| 66 | +t = int(input()) |
| 67 | + |
| 68 | +arr = list(map(int, input().split())) |
| 69 | + |
| 70 | +for i in range(t): |
| 71 | + tree.create(arr[i]) |
| 72 | + |
| 73 | +topView(tree.root) |
0 commit comments