Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. struct node
  4. {
  5. int data;
  6. struct node *left;
  7. struct node *right;
  8. };
  9. struct node *root=NULL;
  10. struct node *create(int item);
  11. void postorder(struct node *root);
  12. void preorder(struct node *root);
  13.  
  14. int main()
  15. {
  16. struct node *root=create(11);
  17. root->left=create(22);
  18. root->right=create(33);
  19. root->left->left=create(44);
  20. root->left->right=create(55);
  21. root->right->left=create(66);
  22. root->right->right=create(77);
  23.  
  24. printf("postorder traversal result\n");
  25. postorder(root);
  26. printf("\n");
  27. printf("preorder traversal result\n");
  28. preorder(root);
  29. }
  30. struct node *create(int item)
  31. {
  32. struct node *temp;
  33. temp=(struct node*)malloc(sizeof(struct node));
  34. temp->data=item;
  35. temp->left=NULL;
  36. temp->right=NULL;
  37. return temp;
  38. }
  39. void postorder(struct node *root)
  40. {
  41. struct node *stack[20],*ptr;
  42. int top=-1;
  43. ptr=root;
  44. while(1)
  45. {
  46. if(ptr!=NULL)
  47. {
  48. stack[++top]=ptr;
  49. ptr=ptr->left;
  50. }
  51. else
  52. {
  53. if(top==-1)
  54. break;
  55. else
  56. {
  57. if(stack[top]->right==NULL)
  58. {
  59. ptr=stack[top--];
  60. printf("%d ",ptr->data);
  61. while(ptr==stack[top]->right)
  62. {
  63. printf("%d ",stack[top]->data);
  64. ptr=stack[top--];
  65. if(top==-1)
  66. break;
  67. }
  68. }
  69. if(top!=-1)
  70. ptr=stack[top]->right;
  71. else
  72. ptr=NULL;
  73. }
  74. }
  75.  
  76. }
  77.  
  78. }
  79. void preorder(struct node *root)
  80. {
  81. struct node *ptr,*stack[20];
  82. int top=-1;
  83. ptr=root;
  84. while(1)
  85. {
  86. while(ptr!=NULL)
  87. {
  88. printf("%d ",ptr->data);
  89. stack[++top]=ptr;
  90. ptr=ptr->left;
  91. }
  92. if(top==-1)
  93. break;
  94. else
  95. {
  96. ptr=stack[top--];
  97. ptr=ptr->right;
  98. }
  99. }
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement