Recover Binary Tree through it preorder and inorder traversal

/***
Given preorder and inorder traversal of a tree, construct the binary tree.
Example:
preorder = {7,10,4,3,1,2,8,11}
inorder = {4,10,3,1,7,11,8,2}
***/

#include<iostream>

using namespace std;

class node {
public:
       int data;
       node *left, *right;
       node(int val) {
              this->data = val;
              this->left = nullptr;
              this->right = nullptr;
       }
};

class binarytree {
public:
       binarytree(int *pre, int *in, int sz) {
              preorder = pre;
              inorder = in;
              size = sz;
       }
       node *getroot();
       void printBT();
private:
       node *constructBT(int &index, int begin, int end);
       int findindex(int val, int begin, int end);
       int *preorder;
       int *inorder;
       int size;
       node *root;  
};

int binarytree::findindex(int val, int begin, int end) {
       for(int i = begin; i<=end; i++) {
              if(inorder[i] == val) return i;
       }
       return -1;
}

node * binarytree::constructBT(int &index, int begin, int end) {    
       if(begin > end) {
              index--;
              return nullptr;
       }

       node *n = new node(preorder[index]);
       if(begin == end) return n;

       node *left, *right;
       int id = findindex(preorder[index], begin, end);
       index++;
       left = constructBT(index, begin, id-1);
       index++;
       right = constructBT(index, id+1, end);

       n->left = left;
       n->right = right;

       return n;    
}

node * binarytree::getroot(){
       int index = 0;
       root = constructBT(index, 0, size-1);
       return root;
}

void printBT(node *root) {
       if (root == nullptr) return;
      
       printBT(root->left);
       cout<<root->data<<" ";
       printBT(root->right);
}

void main() {
       int preorder[] = {7,10,4,3,1,2,8,11};
       int inorder[] = {4,10,3,1,7,11,8,2};
       int sz = sizeof(preorder) / sizeof(int);

       binarytree bt(preorder, inorder, sz);
       node *root = bt.getroot();
       node *p = root;
       printBT(p);

}

Comments

Popular posts from this blog

Sudoku

Longest prefix matching - trie

Climbing Stairs