fork download
  1. #include<stdio.h>
  2. #include<iostream.h>
  3. #include<conio.h>
  4. #include<malloc.h>
  5. struct node
  6. {
  7. int info;
  8. struct node *left;
  9. struct node *right;
  10.  
  11. };
  12. struct node *getnode(int data);
  13. struct node *buildtree(int pre[],int start,int end);
  14. int search(int pre[],int start,int end ,int temp);
  15. void in(struct node *);
  16. int main()
  17. {
  18.  
  19. //int pre[]={10,5,2,7,12,11,13};
  20. //int pre[]={10,2,1,12,13};
  21. //int pre[]={10,2,5,12,11,13};
  22. int n = sizeof(pre)/sizeof(pre[0]);
  23. struct node *root=buildtree(pre,0,n-1);
  24. cout<<"\n\t";
  25. in(root);
  26.  
  27.  
  28.  
  29. getch();
  30. return 0;
  31. }
  32. struct node *getnode(int data)
  33. {
  34. struct node *temp = (struct node *)malloc(sizeof(struct node));
  35. temp->right = temp->left = NULL;
  36. temp->info = data;
  37. return temp;
  38. }
  39. struct node *buildtree(int pre[],int start,int end)
  40. {
  41. static int preindex = 0;
  42. //boundary condition
  43. if(start > end)
  44. return NULL;
  45.  
  46. int temp = pre[preindex++];
  47. struct node *tnode = getnode(temp);
  48. //if no child is present
  49. if(start==end)
  50. return tnode;
  51.  
  52. //search for the first element which is greater than temp which will begin right subtree
  53. int index = search(pre,start,end,temp);
  54. //cout<<"\n index = "<<index;
  55. //cout<<"\n start = "<<start;
  56. tnode->left = buildtree(pre,start + 1,index-1);
  57. tnode->right = buildtree(pre,index,end);
  58.  
  59.  
  60. return tnode;
  61.  
  62.  
  63.  
  64. }
  65.  
  66. int search(int pre[],int start,int end ,int temp)
  67. {
  68. int i;
  69. cout<<"\n temp = "<<temp;
  70. for(i=start;i<=end;i++)
  71. {
  72. if(pre[i] > temp)
  73. return i;
  74.  
  75. }
  76. //cout<<"\n Not found for temp = "<<temp ;
  77. //If no elemnt is found that is der is no right subtree so return i such that start > end will automatically return NULL
  78. return i;
  79.  
  80.  
  81. }
  82. void in(struct node *root)
  83. {
  84. if(root!=NULL)
  85. {
  86. in(root->left);
  87. cout<<" "<<root->info;
  88. in(root->right);
  89. }
  90.  
  91. }
  92.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp:2:21: error: iostream.h: No such file or directory
prog.cpp:3:18: error: conio.h: No such file or directory
prog.cpp: In function ‘int main()’:
prog.cpp:22: error: ‘pre’ was not declared in this scope
prog.cpp:24: error: ‘cout’ was not declared in this scope
prog.cpp:29: error: ‘getch’ was not declared in this scope
prog.cpp: In function ‘int search(int*, int, int, int)’:
prog.cpp:69: error: ‘cout’ was not declared in this scope
prog.cpp: In function ‘void in(node*)’:
prog.cpp:87: error: ‘cout’ was not declared in this scope
stdout
Standard output is empty