Answers for "inserting into binary serach tree"

0

searching display insert in a binary serach tree

#include <iostream>

using namespace std;
class node
{
public:
    int data;
    node*right;
    node*left;
};
node*getnewnode(int val)
{
    node *temp=new node;
    temp->data=val;
    temp->left=NULL;
    temp->right=NULL;
   return temp;
}
node*insertbst(node*root,int val)
{
    if(root==NULL)
    {
        return getnewnode(val);
    }
    if(root->data>val)
    {
        root->left= insertbst(root->left,val);
    }
    else
    {
        root->right= insertbst(root->right,val);
    }
    return root;
}
int searchbst(node*root,int val)
{
    if(root==NULL)
    {
        return 0;
    }
    if(root->data==val)
    {
        return 1;
    }
    if(root->data<val)
    {
        return searchbst(root->right,val);
    }
    else
    {
        return searchbst(root->left,val);
    }
}
void inorder(node*root)
{
    if(root==NULL)
    {
        return;
    }
    inorder(root->left);
    cout<<root->data<<" ";
    inorder(root->right);
}
int main()
{
    node*root=new node;
    root=NULL;
    while(1)
    {
        int value;
        cout<<"1.Insert to bst"<<endl<<"2.search in bst:"<<endl<<"3.display ordered bst"<<endl<<"4. exit"<<endl;
        int n;
        cout<<"enter your choice:"<<endl;
        cin>>n;
        switch(n)
        {
        case 1:
            {
                cout<<"enter the value to be inserted:"<<endl;
                cin>>value;
                root=insertbst(root,value);
                break;
            }
        case 2:
            {
                cout<<"enter the value you want to search:"<<endl;
                int search;
                cin>>search;
                int s=searchbst(root,search);
                if(s==1)
                {
                    cout<<"value found"<<endl;
                }
                else
                {
                    cout<<"value not found:"<<endl;
                }
                break;
            }
        case 3:
            {
                inorder(root);
                cout<<endl;
                break;
            }
        case 4:
            {
                exit(0);
            }
        default:
            {
                cout<<"invalid choice given:"<<endl;
            }

        }
    }
    return 0;
}
Posted by: Guest on May-21-2021
0

insert binary search tree

void BSNode::insert(std::string value) {

	if (this->_data == value) {
		_count++;
		return;
	}

	if (this->_data > value) {
		if (this->getLeft() == nullptr) {
			this->_left = new BSNode(value);
		}
		this->getLeft()->insert(value);
		return;
	}

	if (this->getRight() == nullptr) {
		this->_right = new BSNode(value);
		return;
	}
	this->getRight()->insert(value);
}
Posted by: Guest on January-03-2021

Code answers related to "inserting into binary serach tree"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language