Advertisement
sanpai

Binary tree operations ,inorder ,pre and postorder

Sep 24th, 2012
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<malloc.h>
  3.  
  4.  
  5. struct btree
  6.  
  7. {
  8.  
  9. int info;
  10. struct btree *lchild;
  11. struct btree *rchild;
  12. };
  13.  
  14. struct btree * createbt();
  15. void preorder(struct btree *);
  16. void postorder(struct btree *);
  17. void inorder(struct btree *);
  18. int main()
  19.  
  20. {
  21.  
  22. struct btree *root;
  23. root=NULL;
  24. root=createbt();
  25. printf("\n The preorder traversal \n");
  26. preorder(root);
  27. printf("\n The postorder traversal \n");
  28. postorder(root);
  29. printf("\n The inorder traversal \n");
  30. inorder(root);
  31.  
  32.  
  33.  
  34. }
  35.  
  36. struct btree * createbt()
  37.  
  38. {
  39.  
  40. struct btree *newnode;
  41. newnode=NULL;
  42. int data;
  43. printf("\n Enter the new data ");
  44. scanf("%d",&data);
  45.  
  46. if(data != 999)
  47. {
  48. newnode=(struct btree *)malloc(sizeof(struct btree));
  49. newnode->info=data;
  50. newnode->lchild=NULL;
  51. newnode->rchild=NULL;
  52.  
  53. printf("\n Enter the left child of %d ",data);
  54. newnode->lchild=createbt();
  55.  
  56. printf("\n Enter the right child of %d",data);
  57. newnode->rchild=createbt();
  58. }
  59. return newnode;
  60.  
  61. }
  62.  
  63. void preorder(struct btree *root)
  64. {
  65. if(root!=NULL)
  66. {
  67. printf("%d\n",root->info);
  68. preorder(root->lchild);
  69. preorder(root->rchild);
  70. }
  71.  
  72. }
  73.  
  74. void postorder(struct btree *root)
  75. {
  76.  
  77. if(root!=NULL)
  78. {
  79. postorder(root->lchild);
  80. postorder(root->rchild);
  81. printf("%d\n",root->info);
  82.  
  83. }
  84. }
  85.  
  86. void inorder(struct btree *root)
  87. {
  88.  
  89. if(root!=NULL)
  90. {
  91. inorder(root->lchild);
  92. printf("%d\n",root->info);
  93. inorder(root->rchild);
  94.  
  95.  
  96. }
  97.  
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement