Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding maximum depth of a tree

Tags:

java

tree

I know how to find the depth of a binary tree. But I cannot generalize it to work for any tree.

Can someone please outline a pseudo code for finding the depth of a tree (not necessarily a binary tree).

like image 660
user1801716 Avatar asked Dec 11 '22 17:12

user1801716


2 Answers

int findDepthOfTree(tree):
    int deepest = 0;
    for (child of root node)
       deepest = max(deepest, findDepthOfTree(child))
    return deepest + 1
like image 124
Evan Knowles Avatar answered Dec 24 '22 11:12

Evan Knowles


Java implementation to find depth of a k-ary tree:

static int findDepth(Node root) {
    int deepest = 0;
    if (root.children != null) {
        for (Node child : root.children) {
            deepest = Math.max(deepest, findDepth(child));
        }
    }
    return deepest+1;
}

This assumes the following Node class is implemented to hava a data element as well as a reference to the list of nodes representing its children. Would be something like this:

class Node {
    int data;
    List<Node> children;

    public Node (int data, List<Node> children) {
        this.data = data;
        this.children = children;
    }
    public Node (int data) {
        this.data = data;
        this.children = null;
    }
}
like image 37
lax1089 Avatar answered Dec 24 '22 09:12

lax1089