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).
int findDepthOfTree(tree):
int deepest = 0;
for (child of root node)
deepest = max(deepest, findDepthOfTree(child))
return deepest + 1
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With