编写一个函数 max_depth(root),它接收一个二叉树的根节点 root,并返回二叉树的最大深度。代码是什么
时间: 2023-06-03 16:05:06 浏览: 46
好的,这是一个计算二叉树最大深度的问题。以下是一个 Python 函数的代码示例:
```python
def max_depth(root):
if root is None:
return 0
left_depth = max_depth(root.left)
right_depth = max_depth(root.right)
return max(left_depth, right_depth) + 1
```
其中,如果根节点为空,返回深度0,否则分别计算左子树和右子树的深度,然后取较大值加1作为当前节点深度,最终返回根节点的深度。请注意,实际使用时需要根据具体的二叉树数据结构进行适当调整。
相关问题
Java 如何求解一个二叉树所有节点的深度
要求解一个二叉树所有节点的深度,可以使用递归方法。
首先,需要定义一个递归函数,用于计算二叉树的深度。该函数的输入参数为当前节点和当前深度,输出为当前节点的深度。
然后,在递归函数中,需要分别计算左子树和右子树的深度,并返回其中较大的一个加上 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
```
给定一棵用二叉链表表示的二叉树,其根指针为 root,试写出求二叉树的深度的法。
您好,根据您的描述,您想问如何求二叉树的深度。下面是求二叉树深度的C++代码。请注意,此代码仅适用于用二叉链表表示的二叉树。
```
int getDepth(TreeNode* root) {
if(root == NULL) { // 当前节点为空,深度为0
return 0;
}
int leftDepth = getDepth(root->left); // 递归求左子树深度
int rightDepth = getDepth(root->right); // 递归求右子树深度
return max(leftDepth, rightDepth) + 1; // 返回左右子树深度的最大值加1
}
```
以上代码中,`TreeNode`是表示二叉树节点的结构体,包含左右两个指针和节点值等信息。函数`getDepth`首先判断当前节点是否为空,若为空,则深度为0。否则,分别递归求出左子树的深度和右子树的深度,并返回二者的最大值加1,即为整棵二叉树的深度。
希望能够帮到您,如有疑问请随时提出。