Interview Question
Country: United States
Inorder predecessor will be the answer
public int nextSmall(int val) {
tree = root;
while (tree != null) {
if (tree.value == val) {
node = tree;
break;
} else if (tree.value > val) {
parent = tree;
tree = tree.left;
} else {
parent = tree;
tree = tree.right;
}
}
if (node.left != null) {
if (node.left.right != null) {
return treeMax(node.left.right).value;
} else {
return node.left.value;
}
} else {
return parent.value;
}
}
public int getNextLeastElement(Node root, int n1, int tmp) {
int secondMax=-1,l,r,rootValue;
if(root !=null) {
rootValue=root.getValue();
l=getNextLeastElement(root.getLeft(), n1, tmp);
r=getNextLeastElement(root.getRight(), n1, tmp);
// System.out.println("node is : " + root.getValue() + secondMax);
if( l < r ) {
if(r <n1){
secondMax=r;
}
}
else{
if(l <n1 ){
secondMax=l;
}
}
if(secondMax < rootValue && rootValue <n1)
secondMax=rootValue;
}
return secondMax;
}
private Node findNextLeastNode(Node root)
{
if(root == null) {
return null;
}
if(root.right != null) {
root = root.right;
while(root.left != null) {
root = root.left;
}
}
return root;
}
The run time is of the order of
- Raghav April 07, 2014