Amazon Interview Question
Software Engineer / Developersdo a in-order traversal, with head and tail pointers.
struct node {
int data;
node * left;
node * right;
node(int a) {
data=a; left=NULL; right=NULL;
}
};
node * head=NULL, * tail=NULL;
int cnt;
void bsttodll(node * root) {
if(root==NULL) return;
bsttodll(root->left);
if(head==NULL) {
head = root;
tail = head;
} else {
root->left = tail;
tail->right = root;
tail = root;
}
bsttodll(root->right);
return;
}
int main (int argc, char const* argv[]) {
node * root = new node(7);
root->left = new node(4);
root->right = new node(10);
root->left->left = new node(3);
root->left->right = new node(5);
root->right->left = new node(9);
bsttodll(root);
return 0;
}
i think it is pretty easy :) just do the inorder traversal and accordingly change
see this --
void BSTtoDLL(struct node *r,struct node **head,struct node *prev)
{
if(!r)
return;
BSTtoDLL(r->left,head,prev);
if(!*head)
{
*head=r;
}
else
{
r->left=prev;
prev->right=r;}
prev=r;
BSTtoDLL(r->right,head,prev);
}
where the head is head of linked list
easy... just for each parent do a right rotation and at the same time set prev of parent to left child(if any).
- mrn July 15, 2011