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 create an html page with frames and frameset

1. Write a program to insert a new element at end as well as at a given position in an array in Java

1. To familiarize with network devices like switch, hub, routers and bridges in LaTex