用java实现递归计算树结构当前节点包含多少级
时间: 2023-10-01 22:03:20 浏览: 88
可以用Java实现递归计算树结构当前节点包含多少级,代码如下:
```java
public int getLevel(TreeNode node) {
if (node == null || node.children.isEmpty()) {
return 0;
} else {
int maxChildLevel = 0;
for (TreeNode child : node.children) {
int childLevel = getLevel(child);
if (childLevel > maxChildLevel) {
maxChildLevel = childLevel;
}
}
return maxChildLevel + 1;
}
}
```
其中,`TreeNode` 表示树节点,`node.children` 表示当前节点的子节点列表。该函数的返回值为当前节点包含的最大级数加 1。
示例用法:
```java
// 构造一颗树
TreeNode root = new TreeNode("A");
TreeNode b = new TreeNode("B");
TreeNode c = new TreeNode("C");
TreeNode d = new TreeNode("D");
TreeNode e = new TreeNode("E");
TreeNode f = new TreeNode("F");
TreeNode g = new TreeNode("G");
TreeNode h = new TreeNode("H");
root.addChild(b);
root.addChild(c);
b.addChild(d);
b.addChild(e);
c.addChild(f);
c.addChild(g);
e.addChild(h);
// 计算节点级数
int levelA = getLevel(root);
int levelB = getLevel(b);
int levelC = getLevel(c);
int levelD = getLevel(d);
int levelE = getLevel(e);
int levelF = getLevel(f);
int levelG = getLevel(g);
int levelH = getLevel(h);
// 输出结果
System.out.println("Level of A: " + levelA); // Output: 2
System.out.println("Level of B: " + levelB); // Output: 1
System.out.println("Level of C: " + levelC); // Output: 1
System.out.println("Level of D: " + levelD); // Output: 0
System.out.println("Level of E: " + levelE); // Output: 1
System.out.println("Level of F: " + levelF); // Output: 0
System.out.println("Level of G: " + levelG); // Output: 0
System.out.println("Level of H: " + levelH); // Output: 0
```
阅读全文