Member-only story
Hackerrank In Top 30 MAANG Interview question — Binary Tree — Data Structure
7 min readOct 30, 2020
Binary trees have structure of the nodes where the the left connection of a node is less than the node’s data and the right is greater than the node’s data.
Best known for traversing the structure in preorder, inorder or postorder.
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
# create the tree one node at a time.
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# Create the tree from inputs
tree = BinarySearchTree()# size of the tree
t = int(input())