We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
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
"""
Node is defined as
self.left (the left child of the node)
self.right (the right child of the node)
self.info (the value of the node)
"""
def levelOrder(root):
if not root:
return
queue = [root]
while queue:
cur = queue.pop(0)
print(cur.info, end=" ")
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
tree = BinarySearchTree()
t = int(input())
arr = list(map(int, input().split()))
for i in range(t):
tree.create(arr[i])
levelOrder(tree.root)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
An unexpected error occurred. Please try reloading the page. If problem persists, please contact support@hackerrank.com
Tree: Level Order Traversal
You are viewing a single comment's thread. Return to all comments →
class Node: def init(self, info): self.info = info
self.left = None
self.right = None self.level = None
class BinarySearchTree: def init(self): self.root = None
""" Node is defined as self.left (the left child of the node) self.right (the right child of the node) self.info (the value of the node) """ def levelOrder(root): if not root: return queue = [root] while queue: cur = queue.pop(0) print(cur.info, end=" ") if cur.left: queue.append(cur.left) if cur.right: queue.append(cur.right)
tree = BinarySearchTree() t = int(input())
arr = list(map(int, input().split()))
for i in range(t): tree.create(arr[i])
levelOrder(tree.root)