0% found this document useful (0 votes)
27 views2 pages

Write A Program Which Can Add and Display A Binary Search Tree

This C++ program defines a binary search tree structure with nodes containing data and left/right child pointers. It includes functions to insert nodes, print the tree in inorder traversal, and create new nodes. The main function inserts sample data, prints the inorder traversal both before and after deleting a node, and returns 0.

Uploaded by

Kazi Mostakim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views2 pages

Write A Program Which Can Add and Display A Binary Search Tree

This C++ program defines a binary search tree structure with nodes containing data and left/right child pointers. It includes functions to insert nodes, print the tree in inorder traversal, and create new nodes. The main function inserts sample data, prints the inorder traversal both before and after deleting a node, and returns 0.

Uploaded by

Kazi Mostakim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

1.

Write a program which can add and display a binary search tree

#include <iostream>

using namespace std;

struct node
{
int info;
node *left;
node *right;
};
node *root = NULL;

node* newNode(int d)
{
node *tmp = new node;
tmp->info = d;
tmp->left = NULL;
tmp->right = NULL;
return tmp;
}

void printInorder(node *n)


{
if(n == NULL)
return;

printInorder(n->left);

cout << n->info << endl;

printInorder(n->right);
}

node* insertNode(node *n, int d)


{
if(n == NULL)
{
cout << "inserting : " << d << endl;
return newNode(d);
}
else
{
if(d < n->info)
n->left = insertNode(n->left, d);
else if(d > n->info)
n->right = insertNode(n->right, d);

return n;
}
}

int main()
{
//cout << "Starting";
root = insertNode(root, 25);
insertNode(root, 15);
insertNode(root, 10);
insertNode(root, 50);
insertNode(root, 20);

cout << endl <<endl << "Printing inorder: " <<endl <<endl;
printInorder(root);
deleteNode(root, 25);
cout <<endl <<endl;
printInorder(root);
//cout << root->left->left->info <<endl;
//cout << root->left->info <<endl;
//cout << root->info <<endl;
// cout << root->right->info <<endl;
/*
insertNode(root, 12);
insertNode(root, 10);
insertNode(root, 15);
insertNode(root, 14);

preorderTraversal(root);*/
return 0;
}

You might also like