Reputation: 154
I wrote a method in Java for the successor of a given node in a BST, but it doesn't work
public Node successor(Node selectedNode) {
Node current = root;
while (current.element != selectedNode.element) {
if (selectedNode.element > current.element) {
current = current.right;
} else {
current = current.left;
}
}
if (current.right != null) {
return min(current.right);
} else if (current == max(root)) {
return new Node(Integer.MAX_VALUE);
} else {
Node tmp = current;
if (current.element < root.element) {
current = root;
while (current.left.element > tmp.element) {
current = current.left;
}
} else {
current = root;
while (current.right.element < tmp.element) {
current = current.left;
}
}
return current;
}
}
And the Node class:
public class Node {
public int element;
public Node left;
public Node right;
public Node(int element) {
this.element = element;
this.left = null;
this.right = null;
}
}
My first idea was to write something like this on the else if block, after checking current.right != null
:
Node p = t.parent
while(p != null and t == p:right)
t = p
p = p:parent
return p
But doesn't work.
Upvotes: 0
Views: 60
Reputation: 59174
There are two cases:
Upvotes: 1