GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

Code for deleting a node from a BST (Binary Search Tree)?

#include<iostream>
using namespace std;

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

class BinaryTree{
private:
	node* root;

public:

	node* temp;
	BinaryTree(){
		root=NULL;
		temp=NULL;
	}

	void insert(int n){
		if(root==NULL){
			root=new node;
			root->info=n;
			root->left=NULL;
			root->right=NULL;
			temp=root;
		}
		else{
			node* p=root;
			if(n>root->info){
				if(!setRight(p,n))
					cout<<"Number already exists!"<<endl;
			}
			else if(n<root->info){
				if(!setLeft(p,n))
					cout<<"Number already exists!"<<endl;
			}
			else
				cout<<"Number already exists!"<<endl;
		}
	}

	bool setRight(node* r, int n){
		if(r->right==NULL){
			r->right=new node;
			r->right->info=n;
			r->right->left=NULL;
			r->right->right=NULL;
			return true;
		}
		else{
			if(n>r->right->info)
				setRight(r->right,n);
			else if(n<r->right->info)
				setLeft(r->right,n);
			else
				return false;
		}
		return true;
	}

	bool setLeft(node* l, int n){
		if(l->left==NULL){
			l->left=new node;
			l->left->info=n;
			l->left->left=NULL;
			l->left->right=NULL;
			return true;
		}
		else{
			if(n>l->left->info)
				setRight(l->left,n);
			else if(n<l->left->info)
				setLeft(l->left,n);
			else
				return false;
		}
		return true;
	}

	void print(node* p){
		if(p==NULL){
			return;
		}
		else{
			cout<<p->info<< ' ';
			print(p->left);
			print(p->right);
		}
	}
};
int main(){
	int number_of_elements;
	BinaryTree binaryTree;
	cout<<"Enter how many number you want to enter: ";
	cin>>number_of_elements;

	int number;
	for(int i=1;i<=number_of_elements;i++){
		cout<<"Enter "<< i << " distinct number to insert: ";
		cin>>number;
		binaryTree.insert(number);
	}

	binaryTree.print(binaryTree.temp);
}

This code is about to add new nodes in BST and it also prints the code info by preorder traversal method. I need a code to delete a node from  BST?

asked Oct 28, 2016 by Fahadsheikh
...