searching display insert in a binary serach tree

Solutions on MaxInterview for searching display insert in a binary serach tree by the best coders in the world

showing results for - "searching display insert in a binary serach tree"
Natalia
21 Jul 2016
1#include <iostream>
2
3using namespace std;
4class node
5{
6public:
7    int data;
8    node*right;
9    node*left;
10};
11node*getnewnode(int val)
12{
13    node *temp=new node;
14    temp->data=val;
15    temp->left=NULL;
16    temp->right=NULL;
17   return temp;
18}
19node*insertbst(node*root,int val)
20{
21    if(root==NULL)
22    {
23        return getnewnode(val);
24    }
25    if(root->data>val)
26    {
27        root->left= insertbst(root->left,val);
28    }
29    else
30    {
31        root->right= insertbst(root->right,val);
32    }
33    return root;
34}
35int searchbst(node*root,int val)
36{
37    if(root==NULL)
38    {
39        return 0;
40    }
41    if(root->data==val)
42    {
43        return 1;
44    }
45    if(root->data<val)
46    {
47        return searchbst(root->right,val);
48    }
49    else
50    {
51        return searchbst(root->left,val);
52    }
53}
54void inorder(node*root)
55{
56    if(root==NULL)
57    {
58        return;
59    }
60    inorder(root->left);
61    cout<<root->data<<" ";
62    inorder(root->right);
63}
64int main()
65{
66    node*root=new node;
67    root=NULL;
68    while(1)
69    {
70        int value;
71        cout<<"1.Insert to bst"<<endl<<"2.search in bst:"<<endl<<"3.display ordered bst"<<endl<<"4. exit"<<endl;
72        int n;
73        cout<<"enter your choice:"<<endl;
74        cin>>n;
75        switch(n)
76        {
77        case 1:
78            {
79                cout<<"enter the value to be inserted:"<<endl;
80                cin>>value;
81                root=insertbst(root,value);
82                break;
83            }
84        case 2:
85            {
86                cout<<"enter the value you want to search:"<<endl;
87                int search;
88                cin>>search;
89                int s=searchbst(root,search);
90                if(s==1)
91                {
92                    cout<<"value found"<<endl;
93                }
94                else
95                {
96                    cout<<"value not found:"<<endl;
97                }
98                break;
99            }
100        case 3:
101            {
102                inorder(root);
103                cout<<endl;
104                break;
105            }
106        case 4:
107            {
108                exit(0);
109            }
110        default:
111            {
112                cout<<"invalid choice given:"<<endl;
113            }
114
115        }
116    }
117    return 0;
118}
119