# 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 Sample Output

3 5 1 4 2 6

##### Solution
```/* 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<<" ";
if(root->left!=NULL)
preOrder(root->left);
if(root->right!=NULL)
preOrder(root->right);
}
```
``````# Enter your code here. Read input from STDIN. Print output to STDOUT

class Tree():
def __init__(self,data,left=None,right=None):
self.data = data
self.left = left
self.right = right

def Preorder(root):
if root == None:
return

print root.data,

Preorder(root.left)
Preorder(root.right)

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]))
else:
#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)

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