fork(2) download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. struct node
  4. {
  5. struct node *left;
  6. struct node *right;
  7. int info;
  8. };
  9. struct node *create(struct node *root,int n)
  10. {
  11. if(root==NULL)
  12. {
  13. root=(struct node *)malloc(sizeof(struct node));
  14. root->info=n;
  15. root->left=NULL;
  16. root->right=NULL;
  17. return root;
  18. }
  19. else if(n<root->info)
  20. {
  21. root->left=create(root->left,n);
  22. }
  23. else if(n>root->info)
  24. {
  25. root->right=create(root->right,n);
  26. }
  27. else
  28. printf("\nDUPLICATE ELEMENTS NOT ALLOWED:\n");
  29. return root;
  30. }
  31. int height(struct node *root)
  32. {
  33. if(root==NULL)
  34. return 0;
  35. int left=height(root->left);
  36. int right=height(root->right);
  37. if(left>right)
  38. return left+1;
  39. else
  40. return right+1;
  41. }
  42. void getlevel(struct node *root,int n,int p)
  43. {
  44. if(root==NULL)
  45. return;
  46. if(n==0)
  47. {
  48. printf("%d ",root->info);
  49. return;
  50. }
  51. if(n>0)
  52. {
  53. if(p==1)
  54. {
  55. getlevel(root->left,n-1,p);
  56. getlevel(root->right,n-1,p);
  57. }
  58. if(p==-1)
  59. {
  60. getlevel(root->right,n-1,p);
  61. getlevel(root->left,n-1,p);
  62. }
  63. }
  64. }
  65. void levelorder(struct node *root)
  66. {
  67. int i;
  68. int p=1;
  69. int h=height(root);
  70. for(i=0;i<h;i++)
  71. {
  72. p=(p)*(-1);
  73. getlevel(root,i,p);
  74. }
  75. }
  76. int main()
  77. {
  78. struct node *root=NULL;
  79. int n,p,i;
  80. printf("Enter the number of nodes in the tree:\n");
  81. scanf("%d",&n);
  82. for(i=0;i<n;i++)
  83. {
  84. printf("Enter value of Node:\n");
  85. scanf("%d",&p);
  86. root=create(root,p);
  87. }
  88. printf("Root is ->%d\n",root->info);
  89. levelorder(root);
  90. return 0;
  91. }
Runtime error #stdin #stdout 0s 1792KB
stdin
Standard input is empty
stdout
Standard output is empty