Pre order and Post order traversal in a binary tree – C program

      Binary tree is a tree which has almost two child nodes for each node. It can be traversed by three ways. Preorder, Post order and in order are the three types.  In order traversal is implemented in previous blog post.

Pre order and post order traversals are implemented here….

C implementation:

  • It starts from the including the header files.
  • First, a structure of the node is declared. It has a data, left and right members.
  • ‘create_Node()’  gets the input as data. It allocates the memory. it assigns data and its child data.
  • Preorder Traversal: It follows Root -> Left -> Right principle.
  •  Postorder Traversal: It follows Left -> Right -> Root principle.
  • Finally, main() function calls the functions and display the output.

Code:

#include <stdio.h>

#include <stdlib.h>

// Define the structure of a node

struct b_Node {

    int b_data;

    struct b_Node *t_left, *t_right;

};

// create node function

struct b_Node* create_Node(int b_data) {

    struct b_Node* newNode = (struct b_Node*)malloc(sizeof(struct b_Node));

    newNode->b_data = b_data;

    newNode->t_left = newNode->t_right = NULL;

    return newNode;

}

// Preorder Traversal:

// it follows Root -> Left -> Right principle

void pre_order(struct b_Node* root) {

    if (root == NULL) return;

    printf("%d ", root->b_data);

    pre_order(root->t_left);

    pre_order(root->t_right);

}

// Postorder Traversal:

// It follows Left -> Right -> Root principle

void post_order(struct b_Node* root) {

    if (root == NULL) return;

    post_order(root->t_left);

    post_order(root->t_right);

    printf("%d ", root->b_data);

}

int main() {

    // Create a simple binary tree

    struct b_Node* root = create_Node(1);

    root->t_left = create_Node(2);

    root->t_right = create_Node(3);

    root->t_left->t_left = create_Node(4);

    root->t_left->t_right = create_Node(5);

    root->t_right->t_left = create_Node(6);

    root->t_right->t_right = create_Node(7);

    printf("The Preorder Traversal of the Binary Tree is: ");

    pre_order(root);

    printf("\n The Postorder Traversal of the Binary Tree is: ");

    post_order(root);

 

    return 0;

}

Output:

The Preorder Traversal of the Binary Tree is: 1 2 4 5 3 6 7

 The Post order Traversal of the Binary Tree is: 4 5 2 6 7 3 1

Yes. The concept is implemented. Binary tree with preorder and post order traversal was implemented successfully. Hope, you understood this. Keep Coding!!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

File handling in C++

Employee record management in C