bst.c (1427B)
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 struct Node{ 5 int data; 6 struct Node* left; 7 struct Node* right; 8 }; 9 10 struct Node* initNode(int data){ 11 struct Node *node = malloc(sizeof(struct Node)); 12 node->data = data; 13 node->right = NULL; 14 node->left = NULL; 15 return node; 16 } 17 void insert(struct Node* nd, int data){ 18 if(nd->data < data){ 19 if(nd->left != NULL){ 20 insert(nd->left, data); 21 } 22 else{ 23 struct Node* newNode = initNode(data); 24 nd->left = newNode; 25 } 26 } 27 else{ 28 if(nd->right != NULL){ 29 insert(nd->right, data); 30 } 31 else{ 32 struct Node* newNode = initNode(data); 33 nd->right = newNode; 34 } 35 } 36 } 37 38 void printPostorder(struct Node* nodePtr, int isRoot){ 39 if(nodePtr->left != NULL){ 40 printPostorder(nodePtr->left, 0); 41 } 42 if(nodePtr->right!= NULL){ 43 printPostorder(nodePtr->right, 0); 44 } 45 if(isRoot == 0){ 46 printf("%d, ", nodePtr->data, 0); 47 } 48 else{ 49 printf("%d", nodePtr->data); 50 } 51 } 52 53 54 int main(){ 55 56 struct Node* root = initNode(100); 57 58 int items [] = {10 ,1,2,3,5,34,5543,435,34,543,55,345,353,345,3534,76576,846, -1}; 59 60 for (int i = 0 ; items[i] != -1; ++i){ 61 printf("%d", items[i]); 62 insert(root, items[i]); 63 } 64 printf("\n"); 65 printPostorder(root,1); 66 printf("\n"); 67 68 return 0; 69 }