Program :-
WAP in C++ to find out the preorder,postorder as well as inorder traversal of the binary tree.
Solution :-
// Name :- Bakul Gupta
// Email-id :- bakulgupta11@gmail.com
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int key;
Node *left,*right;
Node(int x)
{
left=NULL;
right=NULL;
key=x;
}
};
void inorder(Node *root)
{
if(root)
{
inorder(root->left);
cout<<root->key<<' ';
inorder(root->right);
}
}
void preorder(Node *root)
{
if(root)
{
cout<<root->key<<' ';
preorder(root->left);
preorder(root->right);
}
}
void postorder(Node *root)
{
if(root)
{
postorder(root->left);
postorder(root->right);
cout<<root->key<<" ";
}
}
int main()
{
Node *root=new Node(10);
root->left=new Node(20);
root->right=new Node(30);
root->left->left=new Node(40);
root->left->right=new Node(50);
cout<<"Inorder traversal is :-";
inorder(root);
cout<<"\n Post order Traversal is :-";
postorder(root);
cout<<"\n Pre Order traversal is :-";
preorder(root);
return 0;
}
Comments
Post a Comment