Interview Questions

180. write a insert function to insert into binary search tree node *insert(node *root);

Microsoft Interview Questions and Answers


(Continued from previous question...)

180. write a insert function to insert into binary search tree node *insert(node *root);

Question:
write a insert function to insert into binary search tree node *insert(node *root);


maybe an answer:


Node * CreateNode(int no)
{
Node *temp = new Node();
temp->no = no;
temp->left = temp->right = NULL;
}
bool Insert(Node **root, int no)
{
if (*root == NULL)
{
*root = CreateNode(no);
return;
}
Node *parent = *root;
Node *tmp = *root;

while (tmp != NULL)
{
if (no < tmp-> no {
parent = tmp;
tmp = tmp->left;
}
else if (no > tmp->no) {
parent = tmp;
tmp = tmp->right;
}
else
{
return false; //dup
}
}
if (no < parent->no)
{
parent->left = CreateNode(no);
return true;
}
else
{
parent->right = CreateNode(no);
return true;
}
}

(Continued on next question...)

Other Interview Questions