Thursday, February 26, 2015

Constructing Binary Tree from In-Order and Pre-Order traversals - C++

/*
Binary Search Tree Implementation in C++
*/
#include<iostream>

using namespace std;

struct node{
char data;

node * left;
node * right;
} *root;


void printTree(node  * root){
if(root){
cout<<"(";
printTree(root->left);
cout<<root->data<<",";
printTree(root->right);
cout<<")";
}
}

int search(char A[], char key, int start, int end){
int pos = -1;
for(int i=start; i<= end; i++){
if(A[i] == key){
pos = i;
break;
}
}

return pos;
}

int preIndex = 0;
node * makeTree(char inOrder[], char preOrder[], int start, int end){
if(start > end){
return NULL;
}
node * temp = new node;
char key = preOrder[preIndex];
temp->data = key;
preIndex++;

if(start == end){
return temp;
}

int inIndex = search(inOrder, key, start, end);
if(inIndex == -1)
{
cout<<"Mismatch in preOrder and inOrder lists";
return NULL;
}

temp->left = makeTree(inOrder, preOrder, start, inIndex-1);
temp->right = makeTree(inOrder, preOrder, inIndex+1, end);
return temp;
}

int main(){
int n = 6;

char inOrder[] = {'D', 'B', 'E', 'A', 'F', 'C'};
char preOrder[] = {'A', 'B', 'D', 'E', 'C', 'F'};

root = makeTree(inOrder,preOrder,0,n-1);
printTree(root);

return 0;
}

No comments:

Post a Comment