BST in C++

Click here to debug the below program.

#include <iostream>

using namespace std;

struct Node
{  
    int num;
    struct Node *left;
    struct Node *right;
};

Node* create_node(int val)
{
   Node* new_node = (Node*)malloc(sizeof(Node));
   new_node->num = val;
   new_node->left = nullptr;
   new_node->right = nullptr;
   return new_node;
}

void insert_node(Node** root, int val)
{
   Node* current = *root;
   if (current == nullptr)
   {
       current = create_node(val);
       *root = current;
       return;
   }
   else {
       if ((*root)->num > val)
       {
          insert_node(&(*root)->left, val);
       } else {
          insert_node(&(*root)->right, val);
       }
   }
}

Node *minValueNode(Node *node) {
  Node *current = node;

  // Find the leftmost leaf
  while (current && current->left != NULL)
    current = current->left;

  return current;
}

// Deleting a node
Node* delete_node(Node *root, int key) {
  // Return if the tree is empty
  if (root == nullptr) return root;

  // Find the node to be deleted
  if (key < root->num)
    root->left = delete_node(root->left, key);
  else if (key > root->num)
    root->right = delete_node(root->right, key);
  else {
    // If the node is with only one child or no child
    if (root->left == NULL) {
      Node *temp = root->right;
      free(root);
      return temp;
    } else if (root->right == NULL) {
      Node *temp = root->left;
      free(root);
      return temp;
    }

    // If the node has two children
    Node *temp = minValueNode(root->right);

    // Place the inorder successor in position of the node to be deleted
    root->num = temp->num;

    // Delete the inorder successor
    root->right = delete_node(root->right, temp->num);
  }
  return root;
}

void inorder(Node* node)
{
    if (node == nullptr)
    {
        return;
    }

    inorder(node->left);
    cout << node->num << " ";
    inorder(node->right);
}

void postorder(Node* node)
{
    if (node == nullptr)
    {
        return;
    }
    inorder(node->left);
    inorder(node->right);
    cout << node->num << " ";
    cout << "\n"; 
}

void preorder(Node* node)
{
    if (node == nullptr)
    {
        return;
    }
    cout << node->num << " ";
    inorder(node->left);
    inorder(node->right);
    cout << "\n"; 
}


int main()
{
    Node* root = nullptr;

    // Insert root Node
    insert_node(&root, 5);
    //inorder(root);

    // Insert nodes at the left and right
    insert_node(&root, 8);
    insert_node(&root, 10);
    insert_node(&root, 2);
    cout << "Inorder Traversal\n";
    inorder(root);
    cout << "\n\nPreorder Traversal\n";
    preorder(root);
    cout << "\n\nPostorder Traversal\n";
    postorder(root);

    // Delete the node
    root = delete_node(root, 8);
    inorder(root);

    return 0;
}


Output:

1
2
Inorder Traversal
2 5 8 10 

Preorder Traversal
5 2 8 10 


Postorder Traversal
2 8 10 5 
2 5 10 



Comments