Skip to content

HackerRank Solutions: Tree: Preorder Traversal

Problem

Complete the  function in the editor below, which has  parameter: a pointer to the root of a binary tree. It must print the values in the tree’s preorder traversal as a single line of space-separated values.

Input Format

Our test code passes the root node of a binary tree to the preOrder function.

Constraints

 Nodes in the tree 

Output Format

Print the tree’s preorder traversal as a single line of space-separated values.

Sample Input

     1
      \
       2
        \
         5
        /  \
       3    6
        \
         4  

Sample Output

1 2 5 3 4 6 

Explanation

The preorder traversal of the binary tree is printed.

Solution

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 preOrder(root):
    #Write your code here
    stack = [root]
    sti = 0
    while (sti < len(stack)):
        currnode = stack[sti]
        if currnode.left:
            stack.insert(sti+1, currnode.left)
            if currnode.right:
                stack.insert(sti+2, currnode.right)
        elif currnode.right:
            stack.insert(sti+1, currnode.right)
        sti += 1
    for s in stack:
        print(s.info, end=' ')

Published inProgramming

Be First to Comment

Leave a Reply