binary search tree sorting code example

Example: binary search tree sorted order

#include <iostream>

using namespace std;
class node
{
public:
    int data;
    node*left;
    node*right;
};
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 if(root->data<val)
    {
        root->right=insertbst(root->right,val);
    }
    return root;
}
void inorder(node*root)
{
    if(root==NULL)
    {
        return;
    }
    else
    {
        inorder(root->left);
        cout<<root->data<<" ";
        inorder(root->right);
    }
}

int main()
{
    node *root=new node;
    root=NULL;
    root=insertbst(root,100);
    root=insertbst(root,200);
    root=insertbst(root,50);
    root=insertbst(root,90);
    root=insertbst(root,150);
    inorder(root);
    return 0;
}

Tags:

Cpp Example