I'm filling up a binary tree, and afterwards I try to get the parent of a certain leaf, trough a recursive method. Each node contains the String data; and let's say i'll only initialize the String data with "*" for each leaf. In that method, i'm traversing trough the tree, until the given node(leaf) has been found, so I can return the parent. After finding a leaf, I want to check if the node(leaf) is identical to the target I was searching for. Sadly, this is not the case, and the method returns the parent first found leaf. I have used .equals() method and the "==" operator, but none of them work. Does anyone know how to solve this problem?
BinaryNode root = new BinaryNode("root",2);
BinaryNode na = new BinaryNode("a",2);
BinaryNode naLeaf1= new BinaryNode("*",0);
BinaryNode naLeaf2 = new BinaryNode("*",0);
na.addChild(naLeaf1);
na.addChild(naLeaf2);
BinaryNode nb = new BinaryNode("b",2);
BinaryNode nbLeaf1= new BinaryNode("*",0);
BinaryNode nbLeaf2 = new BinaryNode("*",0);
nb.addChild(nbLeaf1);
nb.addChild(nbLeaf2);
root.addChild(na);
root.addChild(nb);
This is the recursive method that traverses trough the binary tree.
public BinaryNode getParent(BinaryNode root, BinaryNode target) {
if(root!=null) {
for(BinaryNode ni: root.childeren) {
if(!ni.data.equals("*")) {
return getParent(ni, target);
}else {
if(ni.equals(target)) {
return root;
}
}
}
}
return root;
}
I have added an override for the .equals method, but that doesn't seem to solve the problem.
@Override
public boolean equals(Object target) {
if(target==null) return false;
if(target==this) return true;
if(!(target instanceof BinaryNode)) return false;
return false;
}