简体   繁体   中英

How to get the level of a leaf in a non-binary tree

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  
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM