Posts

Search

Q 103 - Trees - Postorder Traversal

Your task is to implement the following function :

void postorder(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

1 3 2 5 7 6 4 

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 postorder(struct node *root) {
   if (root != NULL) {   
      postorder(root->left);
      postorder(root->right);
      printf("%d ",root->data);
   }
}
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);
   }
   postorder(root);
   return 0;
}