// Tree.cpp : create with my friend Murtada //
#include<iostream>
#include<conio.h>
using namespace std;
class Tree{
struct Node{
Node* Left;
Node* Right;
int data;
Node(int N){
data=N;
Left=Right=NULL;
}
};
Node *Root;
void insertp(int item,Node* &root){
if(root==NULL)
root=new Node(item);
else
if(root->data>item)
insertp(item,root->Left);
else
insertp(item,root->Right);
}
void displaypre(Node *root){
if(root!=NULL){
cout<<root->data<<" ";
if(root->Left!=NULL)
displaypre(root->Left);
if(root->Right!=NULL)
displaypre(root->Right);
}
}
void displayin(Node *root){
if(root->Left!=NULL)
displayin(root->Left);
cout<<root->data<<" ";
if(root->Right!=NULL)
displayin(root->Right);
}
void displaypost(Node *root){
if(root->Left!=NULL)
displaypost(root->Left);
if(root->Right!=NULL)
displaypost(root->Right);
cout<<root->data<<" ";
}
public:
Tree(){
Root=NULL;
}
void insert(int i){ insertp(i,Root);}
void buildtree (int A[],int n){
//int n=7;
insert(A[0]);
//insert(A[(i*2)+1]);
//insert(A[(i*2)+2]);
for (int i=0;i<n;i++){
//insert(A[i]);
if((i*2)+1<n)
insert(A[(i*2)+1]);
if((i*2)+2<n)
insert(A[(i*2)+2]);
}
}
void display(){
cout<<"\npreorder : ";
displaypre(Root);
cout<<"\ninorder : ";
displayin(Root);
cout<<"\npostorder : ";
displaypost(Root);
}
};
void main(){
//cout<<"Murtada and Ahmed ";
Tree t;
t.insert(5);
t.insert(9);
t.insert(7);
t.insert(3);
t.display();
int A[]={5,9,7,3,2,4,6};
t.buildtree(A,7);//n=size of array=7
t.display();
_getch();
}
0 التعليقات:
إرسال تعليق