Posts

Search

Q 102 - Trees - Preorder Traversal

Your task is to implement the following function :

void preorder(TreeNode*)

You will be working with the following structure :

struct TreeNode {
	int x;
    struct TreeNode* L;
    struct TreeNode* R;
}

You may only edit the BODY of the code, leaving the HEAD and the TAIL as it is.

Sample Input 0

7
4 2 1 3 6 7 5

Sample Output 0

4 2 1 3 6 5 7 

Solution :

#include <stdio.h>
#include <stdlib.h>

struct node {
   int data;
   struct node *left;
   struct node *right;
};
struct node *createNode(int val) {
   struct node *temp =  (struct node *)malloc(sizeof(struct node));
   temp->data = val;
   temp->left = temp->right = NULL;
   return temp;
}
void preorder(struct node *root) {
   if (root != NULL) {
      printf("%d ",root->data);
      preorder(root->left);
      preorder(root->right);
   }
}
struct node* insertNode(struct node* node, int val) {   
   if (node == NULL) return createNode(val);
   if (val < node->data)
      node->left  = insertNode(node->left, val);
   else if (val > node->data)
      node->right = insertNode(node->right, val);   
   return node;
}
int main() {
    int val, N; 
    scanf("%d",&N);
   struct node *root = NULL;
   for (int i = 1; i <= N; i++) {
        scanf("%d",&val);
        root = insertNode(root, val);
   }
   preorder(root);
   return 0;
}