Reputation: 39830
I have constructed a Tree class as shown below:
public class Node {
private int label;
private ArrayList<Node> children;
private Node parent;
public Node(int label) {
this.label = label;
this.children = new ArrayList<Node>();
this.parent = null;
}
public void addChild(Node child) {
this.children.add(child);
}
public int getLabel() {
return this.label;
}
public ArrayList<Node> getChildren() {
return this.children;
}
public Node getParent() {
return this.parent;
}
public void setParent(Node parent) {
this.parent = parent;
}
}
Assuming that I have a non binary Tree:
1
|
9
/ | \
3 0 7
How can I write a method in order to get the level of a leaf (say node labelled with 7
) in a non-binary Tree?
public int getLevel() {
if (parent == null) return 0;
// Additional code is needed here
}
Upvotes: 0
Views: 521
Reputation: 1552
The level
is often called the depth or height.
public int getLevel(){
Node temp = parent;
int depth = 0;
while(temp != null){
depth++;
temp = temp.parent;
}
return depth;
}
This will not work if there is a cycle of course, but there shouldn't be one in a tree anyways.
Upvotes: 3