Algorithm: buildTree()
1) Pick an element from Preorder. Increment a Preorder Index Variable (preIndex in below code) to pick next element in next recursive call.
2) Create a new tree node tNode with the data as picked element.
3) Find the picked element’s index in Inorder. Let the index be inIndex.
4) Call buildTree for elements before inIndex and make the built tree as left subtree of tNode.
5) Call buildTree for elements after inIndex and make the built tree as right subtree of tNode.
1) Pick an element from Preorder. Increment a Preorder Index Variable (preIndex in below code) to pick next element in next recursive call.
2) Create a new tree node tNode with the data as picked element.
3) Find the picked element’s index in Inorder. Let the index be inIndex.
4) Call buildTree for elements before inIndex and make the built tree as left subtree of tNode.
5) Call buildTree for elements after inIndex and make the built tree as right subtree of tNode.
6) return tNode.
#include <bits/stdc++.h>
using namespace std;
struct Node {
Node(){}
Node(char data) : data(data) {
left = right = NULL;
}
char data;
Node *left, *right;
};
int Search(char *arr, int inst, int inend, char val) {
for(int i = inst; i <= inend; ++i) {
if(arr[i] == val) {
return i;
}
}
return -1;
}
Node* build(char *in, char *pre, int inst, int inend) {
static int preIndex = 0; // just define when first call build, like a overall variable
Node *tNode = new Node(pre[preIndex++]);
if(inst > inend) {
return NULL;
}
if(inst == inend) {
return tNode;
}
int index = Search(in, inst, inend, tNode->data);
tNode->left = build(in, pre, inst, index-1);
tNode->right = build(in, pre, index+1, inend);
return tNode;
}
void inOrder(Node *t) {
if(t != NULL) {
inOrder(t->left);
cout << t->data << " ";
inOrder(t->right);
}
}
int main(){
ios::sync_with_stdio(false);
char in[] = {'D', 'B', 'E', 'A', 'F', 'C'};
char pre[] = {'A', 'B', 'D', 'E', 'C', 'F'};
int length = sizeof(in) / sizeof(in[0]);
Node *root = build(in, pre, 0, length - 1);
cout << "Inorder traversal of the binary tree is: " << endl;
inOrder(root);
return 0;
}