Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Written Test
Node insert(Node root,int x)
{
if(root==null)
{
Node temp=new Node();
temp.info=x;
if(this.root==null)
this.root=temp;
return temp;
}
else if(root.info<x)
{
root.right=insert(root.right,x);
}
else if(root.info>x)
{
root.left=insert(root.left,x);
}
else
root.equal=insert(root.equal,x);
return root;
}
1.Build the tree recursively.
2.go through all the ancestors .
3.And make the connections while the stack is getting empty.
This program is fortunately working, though I spent a few hours writing it. To add readability to the code, I have added some comments.
The tricky part is when you want to delete a node which has two children (right and left) without having a child which has the same value as the current node has. First find the successor, then swap the node with its successor and after that delete the node ( which you are sure it has at most one child).
- mahdi.oraei February 25, 2014