My project wants me to print out the predecessor and the successor of a binary search tree. The assignment requires me to pass in the data of a node as an argument. When I try to print out the predecessor of a given node's data, it gives me 0. I try tirelessly how to solve the problem and found no where. Hope you can find where the problem lies.
Here is the method:
public void findPredecessor(Node root, int data)
{
int predecessor = 0;
if(root != null)
{
if(root.data == data)
{
if(root.left != null)
{
Node n = root.left;
while(n.right != null) n = n.right;
predecessor= n.data;
}
}
else if(root.data < data)
{
predecessor = root.data;
findPredecessor(root.left, data);
}
}
System.out.print(predecessor);
}
public void printPredecessor(int data)
{
findPredecessor(root, data);
}