Advertisement
saske_7

6_bst(datalab)

Sep 8th, 2017
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.45 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. struct TreeNode{
  4. int info;
  5. struct TreeNode *left;
  6. struct TreeNode *right;
  7.  
  8. };
  9. typedef struct TreeNode BstNode ;
  10. BstNode* GetNode(int item)
  11. {
  12. BstNode* NewNode ;
  13. NewNode = (BstNode*) malloc(sizeof(BstNode));
  14. NewNode-> info = item;
  15. NewNode-> left = NewNode ->right = 0;
  16.  
  17. return NewNode;
  18. }
  19.  
  20.  
  21. BstNode* Insert(BstNode* root,int data ){
  22.  
  23. if(root == 0) {
  24.         root = GetNode(data);
  25.  
  26. }
  27. else if(data <= root-> info ) root-> left = Insert(root-> left ,data);
  28. else root-> right = Insert(root-> right ,data);
  29.  
  30.  
  31. return root;
  32. }
  33.  
  34.  
  35. void preorder(BstNode *root)
  36. {
  37. if(root == 0)
  38.     return ;
  39.      printf("%d ",root->info);
  40. preorder(root->left) ;
  41.  
  42.  
  43.  preorder(root-> right ) ;
  44.  
  45.  
  46.  
  47. }
  48. void postorder(BstNode *root)
  49. {
  50. if(root == 0)
  51.     return ;
  52.   postorder(root->left) ;
  53.   postorder(root-> right ) ;
  54.  
  55.     printf("%d ",root->info);
  56.  
  57.  
  58. }
  59.  
  60. void inorder(BstNode *root)
  61. {
  62. if(root == 0)
  63.     return ;
  64.  
  65.  
  66.   inorder(root->left) ;
  67.   printf("%d ",root->info);
  68.   inorder(root-> right ) ;
  69.  
  70.  
  71. }
  72.  
  73.  
  74.  
  75. int main(){
  76.  // freopen("in.txt","r",stdin);
  77.  // freopen("out.txt","w",stdout);
  78. BstNode *root ;
  79.     root = 0;
  80. int k,j,i ;
  81. printf("how many elements : ");
  82.  
  83. scanf("%d",&k);
  84. for(i = 0; i< k; i++){
  85.   scanf("%d",&j);
  86.   root = Insert(root ,j );
  87. }
  88.  
  89. printf("preorder\n");
  90. preorder(root);
  91.  
  92. printf("\n\npostorder\n");
  93. postorder(root);
  94.  
  95.   printf("\n\ninorder\n");
  96.     inorder(root);
  97.  
  98. return 0;}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement