Tree: Preorder Traversal Hackerrank problem solution

Tree: Preorder Traversal Hackerrank

Complete the preOrder function in your editor below, which has 1 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 hidden tester code passes the root node of a binary tree to your preOrder function.

Output Format

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

Sample Input

Tree: Preorder Traversal Hackerrank

Sample Output

3 5 1 4 2 6

/* you only have to complete the function given below.  
Node is defined as  

struct node
    int data;
    node* left;
    node* right;


void preOrder(node *root) {
   cout<<root->data<<" ";
# Enter your code here. Read input from STDIN. Print output to STDOUT
class Tree():
    def __init__(self,data,left=None,right=None): = data
        self.left = left
        self.right = right
def Preorder(root):
    if root == None:
def heap_to_tree(heap,index=0):
    if len(heap) == 0:
        #print "No tree"
        return None
    elif len(heap) < 2*index + 2:
        #print "    ", heap[index], "is a leaf"
        return Tree(heap[index])
    elif len(heap) == 2*index + 2:
        #print "  adding", heap[2*index+1], "left of", heap[index], "(nothing on right)"
        return Tree(heap[index],Tree(heap[2*index+1]))
        #print "  adding", heap[2*index+1], "left of", heap[index], ".  adding", heap[2*index+2], "right of", heap[index]
        return Tree(heap[index],heap_to_tree(heap,2*index+1),heap_to_tree(heap,2*index+2))
N = input()
data = map(int,raw_input().split())
#print data
root = heap_to_tree(data)

void preOrder(Node root) {
    if(root != null){
        System.out.print( + " ");
def preOrder(root):
    if root != None:
        print(, end=' ')

Click here for more questions related to tree and traversal

All rights reserved. No part of this Post may be copied, distributed, or transmitted in any form or by any means, without the prior written permission of the website admin, except in the case of brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law. For permission requests, write to the owner, addressed “Attention: Permissions Coordinator,” to the

A web developer(Front end and Back end), and DBA at Currently working as Salesforce Developer @ Tech Matrix IT Consulting Private Limited. Check me

Leave a reply:

Your email address will not be published.