Binary Search Tree : Insertion ( Iterative Function )
PROBLEM :
You are given a pointer to the root of a binary search tree and a value to be inserted into the tree. Insert this value into its appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function.
Input Format
You are given a function,
node * insert (node * root ,int value)
{
}
node is defined as :
struct node
{
int data;
node * left;
node * right;
}node;
Output Format
Return the root of the binary search tree after inserting the value into the tree.
Sample Input
4
/ \
2 7
/ \
1 3
The value to be inserted is 6.
Sample Output
4
/ \
2 7
/ \ /
1 3 6
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/*
Node is defined as
typedef struct node
{
int data;
node * left;
node * right;
}node;
*/
node * insert(node * root, int value)
{
node *temp ;
temp=(node*)malloc(sizeof(node)) ;
temp->data=value ;
temp->left=NULL ;
temp->right=NULL ;
if(root==NULL)
return temp ;
node *curr,*parent ;
curr=root ;
while(curr!=NULL)
{
parent=curr ;
if(curr->data<=value)
curr=curr->right ;
else
curr=curr->left ;
}
if(parent->data<=value)
parent->right=temp ;
else
parent->left=temp ;
return root;
}
---------------------------------------------------------------------------------
You are given a pointer to the root of a binary search tree and a value to be inserted into the tree. Insert this value into its appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function.
Input Format
You are given a function,
node * insert (node * root ,int value)
{
}
node is defined as :
struct node
{
int data;
node * left;
node * right;
}node;
Output Format
Return the root of the binary search tree after inserting the value into the tree.
Sample Input
4
/ \
2 7
/ \
1 3
The value to be inserted is 6.
Sample Output
4
/ \
2 7
/ \ /
1 3 6
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/*
Node is defined as
typedef struct node
{
int data;
node * left;
node * right;
}node;
*/
node * insert(node * root, int value)
{
node *temp ;
temp=(node*)malloc(sizeof(node)) ;
temp->data=value ;
temp->left=NULL ;
temp->right=NULL ;
if(root==NULL)
return temp ;
node *curr,*parent ;
curr=root ;
while(curr!=NULL)
{
parent=curr ;
if(curr->data<=value)
curr=curr->right ;
else
curr=curr->left ;
}
if(parent->data<=value)
parent->right=temp ;
else
parent->left=temp ;
return root;
}
---------------------------------------------------------------------------------
Comments
Post a Comment