Advertisement
Singasking

EXPTREE

Nov 20th, 2022
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. //Code to generate expression tree from inorder + preorder
  2. using namespace std;
  3. #include <bits/stdc++.h>
  4. int search(char x,string target,int start,int end) {
  5. for(int i=start;i<=end;i++) {
  6. if(target[i]==x) { return i; }
  7. }
  8. }
  9.  
  10. class Node{
  11. public:
  12.  
  13. char data;
  14. Node *left=NULL;
  15. Node *right = NULL;
  16. Node(char value) { data=value; }
  17. };
  18.  
  19. class ExpTree {
  20. public:
  21. Node* root = NULL;
  22. Node* buildTree(string preorder,string inorder,int startIndex,int endIndex) {
  23. static int preIndex=0;
  24. if(preIndex>=inorder.length()) { return NULL; }
  25. if(startIndex>endIndex) {return NULL; }
  26.  
  27. Node* tempnode = new Node(preorder[preIndex++]);
  28. cout<<"PreIndex is: "<<preIndex<<endl;
  29. cout<<"Node value is : "<<tempnode->data<<endl;
  30. if(startIndex==endIndex) {
  31. //Ie. this node has no children, just return it
  32. return tempnode;
  33. } else {
  34. cout<<"Element is: "<<tempnode->data<<endl;
  35. int splitIndex = search(tempnode->data,inorder,startIndex,endIndex);
  36. cout<<"Split index is: "<<splitIndex<<endl;
  37. tempnode->left = buildTree(preorder,inorder,startIndex,splitIndex-1);
  38. tempnode->right = buildTree(preorder,inorder,splitIndex+1,endIndex);
  39. return tempnode;
  40. }
  41. }
  42. void inorder(Node* node) {
  43. // cout<<node->data<<endl;
  44. //// cout<<node->right->data<<endl;
  45. // return;
  46. if(node==NULL) { return; }
  47. inorder(node->left);
  48. cout<<node->data<<"";
  49. inorder(node->right);
  50. }
  51. void postorder(Node* node) {
  52. // cout<<node->data<<endl;
  53. //// cout<<node->right->data<<endl;
  54. // return;
  55. if(node==NULL) { return; }
  56. postorder(node->left);
  57. postorder(node->right);
  58. cout<<node->data<<"";
  59.  
  60. }
  61.  
  62. void preorder(Node *node) {
  63. if(node==NULL) { return;}
  64. cout<<node->data<<"";
  65. preorder(node->left);
  66. preorder(node->right);
  67. }
  68.  
  69. };
  70. int main() {
  71. ExpTree tree;
  72. string inorder = "DBEAFC";
  73. string preorder = "ABDECF";
  74. tree.root = tree.buildTree(preorder,inorder,0,5);
  75. tree.inorder(tree.root);
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement