Amazon Interview Question
Software Engineer / DevelopersCountry: -
Interview Type: In-Person
As the tree was BST earlier, the parent of node would be greater than the rightmost child of node. So rearrange it like this ;
7
/ \
5 10
/ \ /\
2 6 8 11
/\
1 3
Suppose node is 2
then break 2 -> 5
Arrange 2 -> 3 -> 7.
New tree is
2
/\
1 3
\
7
/\
5 10
\ /\
6 8 11
1. Delete the node just as you would in a normal BST (trivial if node is leaf; splice out the node if it has only one child i.e. replace with child, replace with successor if node has both children).
2. Now compare value of node with value in root. If node value > root value then original root becomes node's left child else it becomes its right child. Finally update root to node.
the answer is rotate to root:
template<typename T>
void insert_root(node*& h, T x) {
if (!h) { h = new node{x}; return }
if (x.key() < h->item.key()
{ insert_root(h->l, x); rotate_right(h); }
else { insert_root(h->r, x); rotate_left(h); }
}
using the usual left or right rotations. ref: algorithms in c++, sedgewick and van wyk.
go thru Split in splay trees
- Anonymous October 17, 2011