SHARE
TWEET

Untitled

a guest Dec 8th, 2019 72 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct my_tree {
  5.     struct my_tree *left;
  6.     struct my_tree *right;
  7.     struct my_tree *parent;
  8.     int key;
  9. } tree;
  10.  
  11.  
  12. tree* add(tree *root, int key) {
  13.     tree *node = root, *node_prev = NULL;
  14.    
  15.     while (node) {
  16.         node_prev = node;
  17.         if (node->key == key) {
  18.             return root;
  19.         }
  20.  
  21.         node = (node->key > key) ? node->left : node->right;
  22.     }
  23.  
  24.     tree *new_node = malloc(sizeof(tree));
  25.     new_node->parent = node_prev;
  26.     new_node->left = NULL;
  27.     new_node->right = NULL;
  28.     new_node->key = key;
  29.  
  30.     if (!node_prev) {
  31.         root = new_node;
  32.     } else if (node_prev->key > key) {
  33.         node_prev->left = new_node;
  34.     } else if (node_prev->key < key) {
  35.         node_prev->right = new_node;
  36.     }
  37.  
  38.     return root;
  39. }
  40.  
  41.  
  42. void print(tree *root) {
  43.     if (root == NULL)
  44.         return;
  45.  
  46.     print(root->left);
  47.     print(root->right);
  48.    
  49.     printf("%d ", root->key);
  50. }
  51.  
  52.  
  53.  
  54.  
  55. int main(void) {
  56.     int val;
  57.     tree *tr = NULL;
  58.  
  59.     scanf("%d", &val);
  60.  
  61.     while(val >= 0) {
  62.         tr = add(tr, val);
  63.         print(tr);
  64.         printf("\n");
  65.         scanf("%d", &val);
  66.  
  67.     }
  68.  
  69.     print(tr);
  70.  
  71.     return 0;
  72. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top