二分木の深さを見つける方法を知っています。しかし、どのツリーでも機能するように一般化することはできません。
誰かが木の深さを見つけるための擬似コードの概要を教えてもらえますか(必ずしも二分木である必要はありません)。
int findDepthOfTree(tree):
int deepest = 0;
for (child of root node)
deepest = max(deepest, findDepthOfTree(child))
return deepest + 1
k-ary ツリーの深さを見つけるための Java 実装:
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;
}
これは、データ要素とその子を表すノードのリストへの参照を持つために、次の Node クラスが実装されていることを前提としています。次のようになります。
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;
}
}