Program to traverse a Binary search tree in Pre-order, In-order and Post-order.

#include<stdlib.h>
#include<iostream>
#include<stdio.h>
using namespace std;
struct node
{
int data;
struct node* left;
struct node* right;
};
struct node* newNode(int data)
{
struct node* node=(struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
void printPostorder(struct node* node)
{
    if(node==NULL)
        return;
printPostorder(node->left);
printPostorder(node->right);
cout<<" "<<node->data;
}
void printInorder(struct node* node)
{
    if (node==NULL)
        return;
    printInorder(node->left);
    cout<<" "<<node->data;
    printInorder(node->right);
}
void printPreorder(struct node* node)
{
    if (node == NULL)
        return;
    cout<<" "<<node->data;
    printPreorder(node->left);
    printPreorder(node->right);
}
int main()
{
struct node *root=newNode(5);
root->left=newNode(22);
root->right=newNode(3);
root->left->left=newNode(9);
root->left->right=newNode(12);
cout<<"Your binary tree is\n 5 22 3 9 12\n";
cout<<"Preorder traversal of binary tree is \n";
printPreorder(root);
cout<<"\nInorder traversal of binary tree is \n";
printInorder(root);
cout<<"\nPostorder traversal of binary tree is \n";
printPostorder(root);
cout<<"\n/*\nName-Sanjampreet Singh\nRoll Number-1507967\n*/";
return 0;
}

Output:


Comments

Popular posts from this blog

To implement the various components of HTML5 Canvas

Program to illustrate the concept of templates.

Program to illustrate the order of execution of constructors and destructors in inheritance.