DATA STRUCTURES



Admission Enquiry Form


Binary Search Tree Using Linked List



Examples of Binary Search Tree Using Linked List

#include<iostream>
using namespace std;
class Node
{
public:
int data;
Node *left;
Node *right;
public:
Node()
{
data=0;
left=nullptr;
right=nullptr;
}
Node(int value)
{
data=value;
left=nullptr;
right=nullptr;
}
};//end of class
Node*  insertNode(Node *root,int value)
{
if(root==nullptr)
{

return new Node(value);
}
if(value<root->data)
{
root->left=insertNode(root->left,value);
}
if(value>root->data)
{
root->right=insertNode(root->right,value);
}
return root;

}//end of function
// Function to traverse the BST (In-order)
void inorderTraversal(Node* root) {
if (root == nullptr) {
return;
}

    inorderTraversal(root->left);
cout << root->data << " ";
inorderTraversal(root->right);
}

// Function to traverse the BST (Pre-order)
void preorderTraversal(Node* root) {
if (root == nullptr) {
return;
}

    cout << root->data << " ";
preorderTraversal(root->left);
preorderTraversal(root->right);
}

// Function to traverse the BST (Post-order)
void postorderTraversal(Node* root) {
if (root == nullptr) {
return;
}

    postorderTraversal(root->left);
postorderTraversal(root->right);
cout << root->data << " ";
}//end of function

int main()
{
Node *root=nullptr;
root=insertNode(root,50);
insertNode(root, 30);
insertNode(root, 20);
insertNode(root, 40);
insertNode(root, 70);
insertNode(root, 60);
insertNode(root, 80);
cout << "In-order traversal: ";
inorderTraversal(root);
cout << endl;

    cout << "Pre-order traversal: ";
preorderTraversal(root);
cout << endl;

    cout << "Post-order traversal: ";
postorderTraversal(root);
cout << endl;

    return 0;
}//end of main

Output: