Finding level of a node on general trees
I'm trying to find the level of a node (which is the root of a subtree itself) in a general tree structure.
The structure definition is (JAVA):
Code:
public class ArbolGeneral {
private Object key = null;
private ArbolGeneral hijoIzq = null; // leftmost child
private ArbolGeneral hnoDer = null; // link to the right node
...
I've successfully found a method to find the height of the tree. This is my implementation:
Code:
public int height(){
int hmax = 0;
if (!isLeaf()) {
ArbolGeneral T = getLeftMostChild();
while (T != null) {
hmax = Math.max(T.height(), hmax);
T = T.getRightNode();
}
}
return hmax+1;
}
But I cannot find a method to, given a tree T, return the level (depth) of the node (subtree-root) ST as:
T.level(ST)
My bad attempt is here:
Code:
public int level(ArbolGeneral T){
int h = 0;
if (this.equals(T))
return h;
if (!isLeaf()){
ArboGeneral LT = getLeftmostChild();
while (LT != null) {
h = LT.level(T);
LT = LT.getRightNode();
}
return h-1;
}
return h + 1;
}
Any ideas? (Note that I don't want the complete result of course... just a point to a good implementation of method)
THANK YOU VERY MUCH :thumb: :wave: