Been trying to solve this for a while now. I've been given a Node in a Disjoint Set.The Node's implementation is as a class where either it has a different parent node or is it's own
class Node {
Node parent;
int rank;
//...constructor and method declarations}
Now, I have to implement the Find method for this class with path compression, called the getParent() method. I wrote the following code:
Node getParent(){
while(parent != this)
{
parent = parent.getParent();
}
return parent;
I get infinite recursion with this code. I know it's problematic, but I do not know how to fix it. I tried using the this
keyword, but it led to the same errors.
Please help. Also, an insight on how to write this code in an iterative manner would be a great plus.
Also, I would like to restructure the tree such that all intermediate nodes between the node on which the getParent() is called and the root have a common parent i.e. the root node.