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,val):
self.value=val
self.left=None
self.right=None
class Tree:
def init(self):
self.root=None
def insert(self,root,val):
if root is None:
return Node(val)
elif root.value>val:
root.left=self.insert(root.left,val)
else:
root.right=self.insert(root.right,val)
return root
def preOrder(self,root):
if root is None:
return
print(root.value,end=' ')
self.preOrder(root.left)
self.preOrder(root.right)
n=int(input())
nums=list(map(int,input().split()))
tree=Tree()
tree.root=Node(nums[0])
for num in nums[1:]:
tree.insert(tree.root,num)
tree.preOrder(tree.root)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Tree: Preorder Traversal
You are viewing a single comment's thread. Return to all comments →
class Node: def init(self,val): self.value=val self.left=None self.right=None
class Tree: def init(self): self.root=None
n=int(input()) nums=list(map(int,input().split())) tree=Tree() tree.root=Node(nums[0]) for num in nums[1:]: tree.insert(tree.root,num) tree.preOrder(tree.root)