in_chainz

Untitled

Dec 20th, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.94 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. struct tree{
  6.     int x;
  7.     struct tree* left;
  8.     struct tree* right;
  9. };
  10.  
  11. int search(struct tree* root, int key) {
  12.     if (root == NULL)
  13.         return 0;
  14.     if (key == root->x)
  15.         return 1;
  16.     if (key > root->x)
  17.         return search(root->right, key);
  18.     else
  19.         return search(root->left, key);
  20. }
  21.  
  22. struct tree* insert(struct tree* root, int key) {
  23.     if (root == NULL) {
  24.         struct tree* node = (struct tree*)malloc(sizeof(struct tree));
  25.         node->x = key;
  26.         node->left = NULL;
  27.         node->right = NULL;
  28.         return node;
  29.     }
  30.     if (key > root->x)
  31.         root->right = insert(root->right, key);
  32.     else
  33.         root->left = insert(root->left, key);
  34.     return root;
  35. }
  36.  
  37. int min(struct tree* root) {
  38.     if (root->left != NULL)
  39.         return min(root->left);
  40.     else
  41.         return root->x;
  42. }
  43.  
  44. struct tree* delete(struct tree* root, int key) {
  45.     if (root == NULL)
  46.         return root;
  47.     if (key < root->x)
  48.         root->left = delete(root->left, key);
  49.     else if (key > root->x)
  50.         root->right = delete(root->right, key);
  51.     else if (root->left != NULL && root->right != NULL) {
  52.         root->x = min(root->right);
  53.         root->right = delete(root->right, root->x);
  54.     }
  55.     else {
  56.         if (root->left != NULL)
  57.             root = root->left;
  58.         else
  59.             root = root->right;
  60.     }
  61.     return root;
  62. }
  63.  
  64. void print(struct tree* root) {
  65.     if (root == NULL)
  66.         return;
  67.     print(root->left);
  68.     printf("%d ", root->x);
  69.     print(root->right);
  70. }
  71.  
  72. int main() {
  73.  
  74.  
  75.     //struct listNode* nd = (struct listNode*)malloc(size + 1);
  76.  
  77.     struct tree* root = NULL;
  78.  
  79.     root = insert(root, 1);
  80.     root = insert(root, 2);
  81.     root = insert(root, 3);
  82.     root = insert(root, 4);
  83.     print(root);
  84.     printf("\n");
  85.     root = delete(root, 3);
  86.     print(root);
  87.  
  88.  
  89.     return 0;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment