Advertisement
Guest User

Untitled

a guest
Mar 29th, 2020
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. typedef struct N
  5. {
  6. int key;
  7. struct N *left;
  8. struct N *right;
  9. } Node;
  10.  
  11.  
  12. typedef struct stack
  13. {
  14. Node *treeNode;
  15. struct stack *next;
  16. } stackNode;
  17.  
  18. Node *CreateBalanced (int N);
  19. void inorder (Node *root);
  20. int isEmpty(stackNode *top);
  21. void push (stackNode **top, Node *v);
  22. void deleteStack(stackNode **top);
  23. void printinOrder ( Node *root);
  24.  
  25. int main()
  26. {
  27. Node *root = NULL;
  28. int n,nr1,nr2;
  29.  
  30. printf("numarul de noduri=");
  31. scanf("%d",&n);
  32. root = CreateBalanced(n);
  33. // printinOrder(root);
  34. inorder(root);
  35.  
  36. return 0;
  37. }
  38.  
  39.  
  40. Node *CreateBalanced (int N)
  41. {
  42. int toAdd;
  43. if(N>0)
  44. {
  45. Node* root = (Node*)malloc(sizeof(Node));
  46. printf("valoare nod=");
  47. scanf("%d",&toAdd);
  48. root->key = toAdd;
  49.  
  50. root->left = CreateBalanced(N/2);
  51. root->right = CreateBalanced(N-1-N/2);
  52. return root;
  53. }
  54. else
  55. return NULL;
  56. }
  57.  
  58. void push (stackNode **top, Node *v)
  59. {
  60. stackNode* newNode = (stackNode*)malloc(sizeof(Node));
  61. newNode->treeNode = v;
  62. newNode->next = *top;
  63. *top = newNode;
  64. }
  65.  
  66. Node* pop(stackNode **top)
  67. {
  68. if(isEmpty(*top))
  69. return NULL;
  70. stackNode *temp = (*top);
  71. Node *aux = temp->treeNode;
  72. *top = (*top)->next;
  73. free(temp);
  74. return aux;
  75. }
  76.  
  77. int isEmpty(stackNode *top)
  78. {
  79. return top == NULL;
  80. }
  81.  
  82. void inorder (Node *root)
  83. {
  84. stackNode *S = NULL;
  85. while(1)
  86. {
  87. while(root)
  88. {
  89. push(&S,root);
  90. root = root->left;
  91. printf("%d",root->key);
  92. }
  93.  
  94.  
  95. if(isEmpty(S))
  96. break;
  97. root = pop(&S);
  98. printf("%d",S->treeNode->key);
  99. root = root->right;
  100. }
  101. deleteStack(&S);
  102. }
  103.  
  104. void deleteStack(stackNode **top)
  105. {
  106. stackNode* topCopy = *top, *temp;
  107. while(topCopy != NULL)
  108. {
  109. temp = topCopy;
  110. topCopy = topCopy->next;
  111. //printf("%d",temp->key);
  112. free(temp);
  113. }
  114. *top = NULL;
  115. }
  116.  
  117. void printinOrder ( Node *root)
  118. {
  119. if(root == NULL)
  120. return;
  121. printinOrder(root->left);
  122. printf("%d ",root->key);
  123. printinOrder(root->right);
  124.  
  125. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement