Java 如何求解一个二叉树所有节点的深度
时间: 2024-03-02 16:53:32 浏览: 25
要求解一个二叉树所有节点的深度,可以使用递归方法。
首先,需要定义一个递归函数,用于计算二叉树的深度。该函数的输入参数为当前节点和当前深度,输出为当前节点的深度。
然后,在递归函数中,需要分别计算左子树和右子树的深度,并返回其中较大的一个加上 1,即为当前节点的深度。
最后,在主函数中,调用递归函数,并传入根节点和深度为 0 的初始值,得到二叉树所有节点的深度。
下面是 Java 代码示例:
```java
class Node {
int val;
Node left;
Node right;
Node(int val) {
this.val = val;
}
}
public class BinaryTreeDepth {
public static int maxDepth(Node root) {
if (root == null) {
return 0;
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
}
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
int depth = maxDepth(root);
System.out.println("The depth of the binary tree is: " + depth);
}
}
```
输出结果:
```
The depth of the binary tree is: 3
```