DEV Community

Cover image for Binary Search Tree in cpp
dk
dk

Posted on

Binary Search Tree in cpp

#define COUNT 10  
struct node
{
    int data;        
    node *left,*right;
};
node *p,*root,*l;
void push()
{
    int x;
    cin>>x;
    p=new node;
    if(root==NULL)
    {
      p->data=x;
      p->left=NULL;
      p->right=NULL;
      root=p;
    }
    else
    {
           p=root;
                 while(p!=NULL)
              {
              if(p->left==NULL && p->data >x)
              {
                  l=new node;
                  p->left=l;
                  l->data=x;
                  l->left=NULL;
                  l->right=NULL;
                  break;
              }
              else if(p->right==NULL && p->data <x)
              {
                  l=new node;
                  p->right=l;
                  l->data=x;
                  l->left=NULL;
                  l->right=NULL;
                   break;
              }
                 else if(p->data > x)
                 {
                     p=p->left;
                 }
                 else 
                 {
                   p=p->right;
                 }

              }
       }
}
void print2DUtil(node *root, int space)  
{  
    if (root == NULL)  
        return;  
    space += COUNT;  
    print2DUtil(root->right, space);  
    cout<<endl;  
    for (int i =  COUNT; i < space; i++)  
        cout<<" ";  
    cout<<root->data<<"\n";  
    print2DUtil(root->left, space);  
}  


void print2D(node *root)  
{  
    print2DUtil(root, 0);  
}  
int main()
{
    root=NULL;
    push();
    push();
    push();
    push();
    push();
    push();
    push();
    print2D(root);

}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)