Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

//Build a Binary Tree by using preorder and inorder Traversal Sequence

#include<iostream>

using namespace std;

class Node{
public:
Node *left,*right;
int data;

public:
Node(){
left=right=NULL;
data=0;
}

Node(int data){
this->data = data;
left=right=NULL;
}
};

int search(int inorder[],int start,int end,int current){


for(int i=start;i<=end;i++){
if(inorder[i] == current)
return i;
}
return -1;
}

Node *makeTree(int preorder[],int inorder[],int start,int end){


static int index = 0;

if(start>end){
return NULL;
}

int current = preorder[index];


index++;

Node *node = new Node(current);

if(start == end){
return node;
}
int position = search(inorder,start,end,current);

node->left = makeTree(preorder,inorder,start,position-1);
node->right = makeTree(preorder,inorder,position+1,end);

return node;
}
void inorderPrint(Node *root){
if(root==NULL)
return;

inorderPrint(root->left);
cout<<" "<<root->data;
inorderPrint(root->right);
}

int main(){

int preorder[] = {1,2,4,8,9,10,11,5,3,6,7};


int inorder[] = {8,4,10,9,11,2,5,1,6,3,7};

Node *root = makeTree(preorder,inorder,0,10);

cout<<"\nTree Generation Success ";


cout<<"\nInorder Traversal of Generated Tree is : ";

inorderPrint(root);

return 0;
}

You might also like