后序遍历求二叉树深度
时间: 2024-06-13 11:07:48 浏览: 9
以下是二叉树后序遍历求深度的Python代码,其中包括递归和非递归两种方法:
1. 递归方法:
```python
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
```
2. 非递归方法:
```python
def tree_depth(root):
if not root:
return 0
stack = [(root, 1)]
max_depth = 0
while stack:
node, depth = stack.pop()
if not node.left and not node.right:
max_depth = max(max_depth, depth)
if node.left:
stack.append((node.left, depth + 1))
if node.right:
stack.append((node.right, depth + 1))
return max_depth
```
相关问题
后序遍历求二叉树深度C语言
以下是C语言实现后序遍历求解二叉树深度的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结构体
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 创建二叉树
TreeNode* createTree() {
int val;
scanf("%d", &val);
if (val == -1) {
return NULL;
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = val;
root->left = createTree();
root->right = createTree();
return root;
}
// 后序遍历求解二叉树深度
int postorderTraversal(TreeNode* root) {
if (root == NULL) {
return 0;
}
int leftDepth = postorderTraversal(root->left);
int rightDepth = postorderTraversal(root->right);
return (leftDepth > rightDepth ? leftDepth : rightDepth) + 1;
}
int main() {
TreeNode* root = createTree();
int depth = postorderTraversal(root);
printf("The depth of the binary tree is: %d\n", depth);
return 0;
}
```
二叉树的基本操作 内容:使用二叉链表存储结构建立一棵二叉树,完成如下功能: 1.创建二叉树 2.先序遍历二叉树 3.中序遍历二叉树 4.后序遍历二叉树 5.求二叉树深度 6.求二叉树叶子结点个数
二叉树是一种常见的树状数据结构,它由节点组成,每个节点最多有两个子节点,分别称为左子节点和右子节点。下面是二叉树的基本操作:
1. 创建二叉树:可以使用二叉链表存储结构来创建二叉树。首先创建一个空的二叉树,然后按照先序遍历的顺序依次添加节点。
2. 先序遍历二叉树:先序遍历是指先访问根节点,然后递归地先序遍历左子树,最后递归地先序遍历右子树。可以使用递归或者栈来实现先序遍历。
3. 中序遍历二叉树:中序遍历是指先递归地中序遍历左子树,然后访问根节点,最后递归地中序遍历右子树。同样可以使用递归或者栈来实现中序遍历。
4. 后序遍历二叉树:后序遍历是指先递归地后序遍历左子树,然后递归地后序遍历右子树,最后访问根节点。同样可以使用递归或者栈来实现后序遍历。
5. 求二叉树深度:二叉树的深度是指从根节点到最远叶子节点的路径上的节点个数。可以使用递归来求解,递归地计算左子树和右子树的深度,然后取较大值加1即可。
6. 求二叉树叶子节点个数:叶子节点是指没有子节点的节点。可以使用递归来求解,递归地计算左子树和右子树的叶子节点个数,然后相加即可。
相关推荐
![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)