I'm creating Binary Search Tree class I got all my functions working accept the Successor.
My tree input is 30 10 45 38 20 50 25 33 8 12
When I print Inorder traversal it come up as
8 10 12 20 25 30 33 38 45 50
When I enter value 8 its says its successor is 12. Same for input 10 and 12 itself.
When I enter value 33 it says successor is 50. Which its not.
I can't seem to fix it. Any help of suggestion will be appreciated.
I'm calling it in main like:
BinarySearchTree BST = new BinarySearchTree(array);
BST.getSeccessor(a); // where a is user input to find it successor
Following is my code...
public TreeNode Successor(TreeNode node) {
if (node == null)
return node;
if (node.right != null) {
return leftMostNode(node.right);
}
TreeNode y = node.parent;
while (null != y && (y.right).equals(node)) {
node = y;
y = y.parent;
}
return y;
}
public static TreeNode leftMostNode(TreeNode node) {
if (null == node) { return null; }
while (null != node.left) {
node = node.left;
}
return node;
}
/** Search value in Tree need for Successor **/
public TreeNode Search(int key) {
TreeNode node = root;
while (node != null) {
if (key < node.value) {
node = node.left;
} else if (key > node.value) {
node = node.right;
}
return node;
}
return null;
}
/** Returns Successor of given value **/
public int getSuccessor(int val) {
TreeNode node = Successor(Search(val));
return node.value;
}