Untitled

 avatar
unknown
plain_text
22 days ago
3.8 kB
1
Indexable
BST:


#include <stdio.h>
#include <stdlib.h>

struct node
{
      int key;
      struct node* left;
      struct node* right;
};

void insert(struct node* tree_root, struct node* node_to_insert);
struct node* find(struct node* tree_root, int key);

struct node* root;

int main()
{
      root = (struct node*)malloc(sizeof(struct node));
      root->key = 60;
      root->left = NULL;
      root->right = NULL;

      struct node* new_el = (struct node*)malloc(sizeof(struct node));
      new_el->key = 50;
      new_el->left = NULL;
      new_el->right = NULL;

      struct node* new_el2 = (struct node*)malloc(sizeof(struct node));
      new_el2->key = 70;
      new_el2->left = NULL;
      new_el2->right = NULL;

      insert(root, new_el);
      insert(root, new_el2);

      struct node* found_element = find(root, 70);

      printf("root: %d\n", root->key);
      printf("root->left: %d\n", root->left->key);
      printf("root->right: %d\n", root->right->key);
      printf("found: %d\n", found_element->key);

      return 0;
}

void insert(struct node* tree_root, struct node* node_to_insert)
{
      if (tree_root == NULL)
      {
            tree_root = node_to_insert;
      }
      if (tree_root->key == node_to_insert->key)
      {
            return;
      }

      if (tree_root->key > node_to_insert->key)
      {
            // Left
            if (tree_root->left == NULL)
            {
                  tree_root->left = node_to_insert;
                  return;
            }
            else
            {
                  return insert(tree_root->left, node_to_insert);
            }
      }
      else
      {
            // Right
            if (tree_root->right == NULL)
            {
                  tree_root->right = node_to_insert;
                  return;
            }
            else
            {
                  return insert(tree_root->right, node_to_insert);
            }
      }
}
struct node* find(struct node* tree_root, int key)
{
      if (tree_root == NULL)
      {
            return NULL;
      }

      if (tree_root->key == key)
      {
            return tree_root;
      }

      if (tree_root->key > key)
      {
            // Left
            return find(tree_root->left, key);
      }
      else
      {
            // Right
            return find(tree_root->right, key);
      }
}
Leave a Comment