Java 如何求解树所有节点的深度
时间: 2024-03-02 07:53:36 浏览: 21
要求解一棵树所有节点的深度,可以使用递归方法。
首先,需要定义一个递归函数,用于计算树的深度。该函数的输入参数为当前节点和当前深度,输出为当前节点的深度。
然后,在递归函数中,需要遍历当前节点的所有子节点,并计算每个子节点的深度。遍历完所有子节点后,返回子节点深度的最大值加上 1,即为当前节点的深度。
最后,在主函数中,调用递归函数,并传入根节点和深度为 0 的初始值,得到树所有节点的深度。
下面是 Java 代码示例:
```java
class TreeNode {
int val;
List<TreeNode> children;
TreeNode(int val) {
this.val = val;
children = new ArrayList<>();
}
}
public class TreeDepth {
public static int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int maxChildDepth = 0;
for (TreeNode child : root.children) {
maxChildDepth = Math.max(maxChildDepth, maxDepth(child));
}
return maxChildDepth + 1;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.children.add(new TreeNode(2));
root.children.add(new TreeNode(3));
root.children.get(0).children.add(new TreeNode(4));
root.children.get(0).children.add(new TreeNode(5));
root.children.get(1).children.add(new TreeNode(6));
int depth = maxDepth(root);
System.out.println("The depth of the tree is: " + depth);
}
}
```
输出结果:
```
The depth of the tree is: 3
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)