fork(2) download
  1. #include <stdbool.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5.  
  6. struct node {
  7. int data;
  8. struct node* left;
  9. struct node* right;
  10. };
  11.  
  12. /* Compute the "height" of a tree -- */
  13. int height(struct node *root)
  14. {
  15. if(!root)
  16. return 0;
  17. else {
  18. /* compute the height of each subtree */
  19. int lheight = height(root->left);
  20. int rheight = height(root->right);
  21. return (lheight >rheight)?(lheight+1): (rheight+1);
  22. }
  23. }
  24.  
  25. //Create a new node
  26. struct node* newNode(int data)
  27. {
  28. struct node *temp = (struct node*)
  29. malloc(sizeof(struct node));
  30. temp->data = data;
  31. temp->left = NULL;
  32. temp->right = NULL;
  33. return temp;
  34. }
  35.  
  36. /* Print nodes at a given level */
  37. void printGivenLevel(struct node* root, int level, int flag)
  38. {
  39. if(!root)
  40. return;
  41. if(level == 1)
  42. printf("%d ", root->data);
  43. else if (level > 1) {
  44. if (flag) {
  45. printGivenLevel(root->left, level - 1, flag);
  46. printGivenLevel(root->right, level - 1, flag);
  47. }
  48. else {
  49. printGivenLevel(root->right, level - 1, flag);
  50. printGivenLevel(root->left, level - 1, flag);
  51. }
  52. }
  53. }
  54.  
  55. /* Function to print spiral traversal of a tree*/
  56. void printSpiral(struct node* root)
  57. {
  58. // get height of the tree
  59. int h = height(root);
  60. int i;
  61.  
  62. /*flag -> Left to Right. If this variable is set,
  63.   then the given level is traversed from left to right. */
  64. int flag = 0;
  65. for (i = 1; i <= h; i++) {
  66. printGivenLevel(root, i, flag);
  67.  
  68. /*change flag value to traverse next level in opposite order*/
  69. flag = !flag;
  70. }
  71. }
  72.  
  73. int main()
  74. {
  75. struct node* root = newNode(10);
  76. root->left = newNode(20);
  77. root->right = newNode(30);
  78. root->left->left = newNode(70);
  79. root->left->right = newNode(60);
  80. root->right->left = newNode(50);
  81. root->right->right = newNode(40);
  82. printf("Spiral Order traversal of binary tree is \n");
  83. printSpiral(root);
  84.  
  85. return 0;
  86. }
  87.  
Success #stdin #stdout 0s 4512KB
stdin
Standard input is empty
stdout
Spiral Order traversal of binary tree is 
10 20 30 40 50 60 70