编写函数计算二叉树的深度。二叉树采用二叉链表存储结构
时间: 2024-01-23 12:40:55 浏览: 37
好的,可以使用递归实现二叉树的深度计算。具体的实现代码如下:
```python
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def tree_depth(root):
if not root:
return 0
left_depth = tree_depth(root.left)
right_depth = tree_depth(root.right)
return max(left_depth, right_depth) + 1
```
其中,Node类表示二叉树节点,val为节点的值,left和right分别表示左右子节点。tree_depth函数计算二叉树的深度,参数root为二叉树的根节点。如果二叉树为空,深度为0;否则,递归计算左右子树的深度,取其最大值再加1即为整棵树的深度。
希望能够帮助您解决问题,如有其他问题欢迎继续提出。
相关问题
二叉树采用二叉链表存储,要求编写算法计算二叉树的高度
好的,针对您的问题,我可以给您提供以下算法计算二叉树的高度:
1. 判断树是否为空,若为空则树的高度为0;
2. 若树不为空,则递归地求左子树和右子树的高度,将两者的最大值加1即为整棵树的高度。
下面是一份采用 Python 实现的代码示例:
```
class BinaryTree:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def tree_height(node):
if node is None:
return 0
else:
left_height = tree_height(node.left)
right_height = tree_height(node.right)
return max(left_height, right_height) + 1
root = BinaryTree(5,
left=BinaryTree(3, left=BinaryTree(2), right=BinaryTree(4)),
right=BinaryTree(7, left=BinaryTree(6), right=BinaryTree(8)))
print(tree_height(root)) # 输出结果为 3
```
希望以上代码可以帮助您解决问题,如果还有不明白的地方请不要犹豫告诉我。
二叉树采用二叉链表存储,要求编写算法计算二叉树的高度(深度)
您好,针对您的问题,我可以给出以下算法来计算二叉树的高度:
1. 如果二叉树为空,则二叉树的高度为0
2. 如果二叉树不为空,则二叉树的高度为左右子树高度的最大值加1。
具体算法实现如下:
```
int getHeight(Node* root) {
if (root == NULL) {
return 0;
} else {
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);
return max(leftHeight, rightHeight) + 1;
}
}
```
其中, Node 是二叉树中的节点结构体,包括左右子节点指针以及存储的元素值。
希望以上回答可以对您有所帮助。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)