Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Node:
- def __init__(self, info):
- self.info = info
- self.left = None
- self.right = None
- self.level = None
- def __str__(self):
- return str(self.info)
- class BinarySearchTree:
- def __init__(self):
- self.root = None
- def create(self, val):
- if self.root == None:
- self.root = Node(val)
- else:
- current = self.root
- while True:
- if val < current.info:
- if current.left:
- current = current.left
- else:
- current.left = Node(val)
- break
- elif val > current.info:
- if current.right:
- current = current.right
- else:
- current.right = Node(val)
- break
- else:
- break
- def findMaxMin(root, max, min, hd = 0):
- if root is None:
- return
- if hd < min[0]:
- min[0] = hd
- elif hd > max[0]:
- max[0] = hd
- findMaxMin(root.left, max, min, hd-1)
- findMaxMin(root.right, max, min, hd+1)
- def VerticalTree(root, node_no, node_dict, hd=0):
- if root is None:return
- if node_no == hd:
- node_dict[node_no].append(root.info)
- VerticalTree(root.left, node_no, node_dict, hd-1)
- VerticalTree(root.right, node_no, node_dict, hd+1)
- def printTopView(node_dict, max, min):
- for line_no in range(min[0], max[0]+1):
- print(node_dict[line_no][0], end=' ')
- def topView(root):
- max, min = [0], [0]
- findMaxMin(root, max, min)
- node_dict = {}
- for node_no in range(min[0], max[0]+1):
- node_dict[node_no] = []
- for node_no in range(min[0], max[0]+1):
- VerticalTree(root, node_no, node_dict)
- printTopView(node_dict, max, min)
- if __name__ == "__main__":
- tree = BinarySearchTree()
- t = int(input())
- arr = list(map(int, input().split()))
- for i in range(t):
- tree.create(arr[i])
- topView(tree.root)
Add Comment
Please, Sign In to add comment