Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Code to generate expression tree from inorder + preorder
- using namespace std;
- #include <bits/stdc++.h>
- int search(char x,string target,int start,int end) {
- for(int i=start;i<=end;i++) {
- if(target[i]==x) { return i; }
- }
- }
- class Node{
- public:
- char data;
- Node *left=NULL;
- Node *right = NULL;
- Node(char value) { data=value; }
- };
- class ExpTree {
- public:
- Node* root = NULL;
- Node* buildTree(string preorder,string inorder,int startIndex,int endIndex) {
- static int preIndex=0;
- if(preIndex>=inorder.length()) { return NULL; }
- if(startIndex>endIndex) {return NULL; }
- Node* tempnode = new Node(preorder[preIndex++]);
- cout<<"PreIndex is: "<<preIndex<<endl;
- cout<<"Node value is : "<<tempnode->data<<endl;
- if(startIndex==endIndex) {
- //Ie. this node has no children, just return it
- return tempnode;
- } else {
- cout<<"Element is: "<<tempnode->data<<endl;
- int splitIndex = search(tempnode->data,inorder,startIndex,endIndex);
- cout<<"Split index is: "<<splitIndex<<endl;
- tempnode->left = buildTree(preorder,inorder,startIndex,splitIndex-1);
- tempnode->right = buildTree(preorder,inorder,splitIndex+1,endIndex);
- return tempnode;
- }
- }
- void inorder(Node* node) {
- // cout<<node->data<<endl;
- //// cout<<node->right->data<<endl;
- // return;
- if(node==NULL) { return; }
- inorder(node->left);
- cout<<node->data<<"";
- inorder(node->right);
- }
- void postorder(Node* node) {
- // cout<<node->data<<endl;
- //// cout<<node->right->data<<endl;
- // return;
- if(node==NULL) { return; }
- postorder(node->left);
- postorder(node->right);
- cout<<node->data<<"";
- }
- void preorder(Node *node) {
- if(node==NULL) { return;}
- cout<<node->data<<"";
- preorder(node->left);
- preorder(node->right);
- }
- };
- int main() {
- ExpTree tree;
- string inorder = "DBEAFC";
- string preorder = "ABDECF";
- tree.root = tree.buildTree(preorder,inorder,0,5);
- tree.inorder(tree.root);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement