fork(1) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define MAX 500
  4.  
  5. struct node
  6. {
  7. int data;
  8. struct node *left;
  9. struct node *right;
  10. };
  11.  
  12. struct node *newNode(int data)
  13. {
  14. struct node *temp = (struct node *)malloc(sizeof(struct node));
  15. temp->data = data;
  16. temp->left = temp->right = NULL;
  17. return temp;
  18. }
  19.  
  20. struct node **createStack(int *top)
  21. {
  22. struct node **stack = (struct node **)malloc(sizeof(struct node *)*MAX);
  23. *top = -1;
  24. return stack;
  25. }
  26.  
  27. void push(struct node **stack, struct node *node, int *top)
  28. {
  29. stack[++(*top)] = node;
  30. }
  31.  
  32. struct node *pop(struct node **stack, int *top)
  33. {
  34. return stack[(*top)--];
  35. }
  36.  
  37. int isStackEmpty(int *top)
  38. {
  39. return (*top == -1);
  40. }
  41.  
  42. void ZigZagTraversal(struct node *root)
  43. {
  44. int top1, top2, top;
  45. struct node **stack1 = createStack(&top1);
  46. struct node **stack2 = createStack(&top2);
  47. struct node *temp;
  48. push(stack1, root, &top1);
  49. while(!isStackEmpty(&top1) || !isStackEmpty(&top2))
  50. {
  51. while(!isStackEmpty(&top1))
  52. {
  53. temp = pop(stack1, &top1);
  54. printf("%d\t", temp->data);
  55. if(temp->right)
  56. push(stack2, temp->right, &top2);
  57. if(temp->left)
  58. push(stack2, temp->left, &top2);
  59. }
  60. while(!isStackEmpty(&top2))
  61. {
  62. temp = pop(stack2, &top2);
  63. printf("%d\t", temp->data);
  64. if(temp->left)
  65. push(stack1, temp->left, &top1);
  66. if(temp->right)
  67. push(stack1, temp->right, &top1);
  68. }
  69. }
  70. }
  71.  
  72.  
  73. int main()
  74. {
  75. struct node *root=NULL;
  76. root = newNode(10);
  77. root->left = newNode(20);
  78. root->right = newNode(30);
  79. root->left->left = newNode(40);
  80. root->right->left = newNode(50);
  81. root->right->right = newNode(60);
  82. ZigZagTraversal(root);
  83. return 0;
  84. }
  85.  
  86. /* Time complexity is O(n) and space complexity is O(n) */
  87.  
Success #stdin #stdout 0s 4544KB
stdin
Standard input is empty
stdout
10	20	30	60	50	40