C语言使用递归或者非递归的方式实现二叉树的遍历,要求输入为二叉树各节点的值,输出为建立二叉树的深度
时间: 2024-02-26 13:56:31 浏览: 21
好的,我来为您介绍一下如何在 C 语言中使用递归或者非递归的方式实现二叉树的遍历,并统计二叉树的深度。
首先,我们需要定义二叉树的结构体:
```c
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
```
接下来,我们分别介绍递归和非递归实现二叉树的先序遍历、中序遍历和后序遍历,并在实现过程中统计深度。
## 递归实现
先序遍历:
```c
int preorder(TreeNode* root, int depth) {
if (root) {
printf("%d ", root->val);
depth++;
depth = preorder(root->left, depth);
depth = preorder(root->right, depth);
}
return depth;
}
```
中序遍历:
```c
int inorder(TreeNode* root, int depth) {
if (root) {
depth = inorder(root->left, depth);
printf("%d ", root->val);
depth++;
depth = inorder(root->right, depth);
}
return depth;
}
```
后序遍历:
```c
int postorder(TreeNode* root, int depth) {
if (root) {
depth = postorder(root->left, depth);
depth = postorder(root->right, depth);
printf("%d ", root->val);
depth++;
}
return depth;
}
```
## 非递归实现
先序遍历:
```c
int preorder(TreeNode* root) {
int depth = 0;
TreeNode* stack[1000];
int top = -1;
stack[++top] = root;
while (top >= 0) {
TreeNode* node = stack[top--];
if (node) {
printf("%d ", node->val);
depth++;
stack[++top] = node->right;
stack[++top] = node->left;
}
}
return depth;
}
```
中序遍历:
```c
int inorder(TreeNode* root) {
int depth = 0;
TreeNode* stack[1000];
int top = -1;
TreeNode* node = root;
while (node || top >= 0) {
while (node) {
stack[++top] = node;
node = node->left;
}
node = stack[top--];
printf("%d ", node->val);
depth++;
node = node->right;
}
return depth;
}
```
后序遍历:
```c
int postorder(TreeNode* root) {
int depth = 0;
TreeNode* stack[1000];
int top = -1;
TreeNode* node = root;
TreeNode* lastVisited = NULL;
while (node || top >= 0) {
while (node) {
stack[++top] = node;
node = node->left;
}
node = stack[top];
if (node->right && node->right != lastVisited) {
node = node->right;
} else {
printf("%d ", node->val);
depth++;
top--;
lastVisited = node;
node = NULL;
}
}
return depth;
}
```
以上就是在 C 语言中使用递归或者非递归的方式实现二叉树的遍历,并统计二叉树的深度的方法。希望能对您有所帮助!