写出求二叉树深度的算法
时间: 2023-12-01 20:04:33 浏览: 48
一种求二叉树深度的算法是使用递归实现。具体步骤如下:
1. 如果二叉树为空,则深度为0。
2. 否则,递归地计算左子树和右子树的深度。
3. 取左右子树深度的最大值,并加上1(根节点的深度),即为整棵二叉树的深度。
以下是使用 Python 语言实现的代码示例:
```
class Node:
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = right
def maxDepth(root) -> int:
if not root:
return 0
left_depth = maxDepth(root.left)
right_depth = maxDepth(root.right)
return max(left_depth, right_depth) + 1
```
其中,`Node` 类表示二叉树节点,`maxDepth` 函数接收一个二叉树的根节点作为参数,返回二叉树的深度。
相关问题
请简要写出利用递归算法求取二叉树深度的过程
递归算法求取二叉树深度的过程如下:
1. 如果二叉树为空,则深度为0,返回0。
2. 如果二叉树不为空,求出左子树的深度和右子树的深度。
3. 以左子树深度和右子树深度中较大的一个为准,加1,即为整棵二叉树的深度。
4. 返回整棵树的深度。
递归算法的实现方式是,首先判断当前节点是否为空,如果为空则返回0;如果不为空,则递归求解左子树和右子树的深度,然后将左右子树的深度较大的一个加1即为整棵树的深度。
伪代码实现如下:
```
function treeDepth(node):
if node == null:
return 0
else:
leftDepth = treeDepth(node.left)
rightDepth = treeDepth(node.right)
return max(leftDepth, rightDepth) + 1
```
其中,`node`为当前节点,`node.left`和`node.right`分别为当前节点的左子树和右子树。函数返回值为整棵树的深度。
试写出二叉树的二叉链储存结构描述,并给出求深度算法
二叉树的二叉链表存储结构定义如下:
```
typedef struct BiTNode {
int data; // 数据域
struct BiTNode *lchild; // 左孩子指针
struct BiTNode *rchild; // 右孩子指针
} BiTNode, *BiTree;
```
求取二叉树深度的算法如下:
```
int GetDepth(BiTree T) {
if(T == NULL) { // 空树深度为0
return 0;
}
int left_depth = GetDepth(T->lchild); // 左子树深度
int right_depth = GetDepth(T->rchild); // 右子树深度
return left_depth > right_depth ? left_depth + 1 : right_depth + 1;
}
```
以上算法采用递归方式实现,时间复杂度为O(n),其中n为二叉树中节点数。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.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)