Amazon Interview Question
SDE1sTeam: Kindle
Country: India
Interview Type: In-Person
a quick and dirty solution with a global variable. This is a recursive approach by modifying the inorder traversal algorithm.
Node *current = NULL;
void fillSuccessors(Node *root)
{
if(root == NULL)
{
return;
}
else
{
fillSuccessors(root->left);
if(!current)
{
current = root;
}
}
else
{
current->next = root;
current = root;
}
fillSuccessors(root->right);
}
}
a quick and dirty solution with a global variable. This is a recursive approach by modifying the inorder traversal algorithm.
Node *current = NULL;
void fillSuccessors(Node *root)
{
if(root == NULL)
{
return;
}
else
{
fillSuccessors(root->left);
if(!current)
{
current = root;
}
}
else
{
current->next = root;
current = root;
}
fillSuccessors(root->right);
}
}
Assumption is that BST already contains val
public Integer inOrderSuccessor(Integer val) {
return inOrderSuccessor(root, val);
}
public Integer inOrderSuccessor(Node n, Integer val) {
if (n == null)
return null;
boolean left = false;
boolean right = false;
Integer ret = null;
if (n.val == val) {
left = true;
right = true;
} else if (val < n.val) {
ret = inOrderSuccessor(n.left, val);
right = true;
} else if (val > n.val) {
ret = inOrderSuccessor(n.right, val);
}
if (ret != null)
return ret;
if (left && n.left != null)
return new Integer(n.left.val);
if (right && n.right != null)
return new Integer(n.right.val);
return null;
}
Here is a possible solution :
- EPavlova April 23, 2015{{
void populateInOrderSuccessor() {
Stack<Node> stack = new Stack<>();
stack.push(root);
Node current = root.left;
Node prev = null;
boolean finish = false;
while (!finish) {
if (current != null) {
stack.push(current);
current = current.left;
}
else {
if(!stack.isEmpty()) {
Node top = stack.pop();
if (prev != null){
prev.next = top;
}
prev = top;
if(top.right!=null) {
current = top.right;
}
}
else
finish = true;
}
}
}
}
}}