Question:
My code below (doesn't work):
public K from(K k, int i) throws NotFound {
//reset stack
parentNode = new Stack<Node<K>>();
//Returns node with value k
Node<K> foundNode = findNode(k, root);
return fromHelper(k, i, foundNode);
}
public K fromHelper(K k, int i, Node<K> v) throws NotFound {
if ( v == null ) {
throw new NotFound();
}
else if (i == 0) {
return v.key;
}
//Case 3: left tree exists
if (v.left != null) {
if (k.compareTo(v.left.key) < 0) {
return fromHelper(k, i-1, v.left);
}
}
//Case 2: Right tree exists
if (v.right != null) {
return fromHelper(k, i-1, v.right);
}
if (!parentNode.isEmpty()) {
//Pop parent node
Node<K> parent = parentNode.pop();
if (k.compareTo(parent.key) < 0) {
return fromHelper(k, i-1, parent);
}
else {
throw new NotFound();
}
}
else {
throw new NotFound();
}
}
I am completely lost for this question. I absolutely CANNOT figure out a way to get an algorithm that run in O(log(n)) time. The ONLY algorithm I can think of is to do an in-order traversal, store values in an array and then return the ith smallest key greater than k if it exists but obviously this is worst case O(n). I have been working on this problem for the past 2 days and I simply cannot come up with a solution. The hint my professor gave me was to add a size field to the node which will tell me the number of nodes at subtree v including itself. My thinking was to try to use a relative_rank function (gives me the rank of node value k with respect to a node v) somehow but I cannot think of a way to do it in O(log(n)) time. Any help would be appreciated.