画出自己的一颗二叉树,给出输入序列;把中序或后序的遍历算法改为非递归算法;给出遍历序列。
时间: 2025-01-05 21:41:49 浏览: 4
好的,我来为您解答这个问题,并提供相应的C语言代码实现。
1. 画出二叉树并给出输入序列
我们可以先定义一个简单的二叉树结构:
```c
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode* createTree() {
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = 1;
root->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->val = 2;
root->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->val = 3;
root->left->left = NULL;
root->left->right = NULL;
root->right->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->left->val = 4;
root->right->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->right->val = 5;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right->left = NULL;
root->right->right->right = NULL;
return root;
}
```
这个函数创建了一棵简单的二叉树:
```
1
/ \
2 3
/ \
4 5
```
输入序列就是创建这棵树的顺序:[1, 2, 3, 4, 5]
2. 将中序遍历改为非递归算法
中序遍历的非递归实现通常使用栈:
```c
void inorderTraversal(struct TreeNode* root) {
struct TreeNode* current = root;
struct TreeNode* stack[100];
int top = -1;
while (current != NULL || top != -1) {
while (current != NULL) {
stack[++top] = current;
current = current->left;
}
current = stack[top--];
printf("%d ", current->val);
current = current->right;
}
}
```
3. 将后序遍历改为非递归算法
后序遍历的非递归实现稍微复杂一些,可以使用两个栈:
```c
void postorderTraversal(struct TreeNode* root) {
if (root == NULL) return;
struct TreeNode* stack1[100];
struct TreeNode* stack2[100];
int top1 = -1, top2 = -1;
stack1[++top1] = root;
while (top1 != -1) {
struct TreeNode* node = stack1[top1--];
stack2[++top2] = node;
if (node->left != NULL) {
stack1[++top1] = node->left;
}
if (node->right != NULL) {
stack1[++top1] = node->right;
}
}
while (top2 != -1) {
struct TreeNode* node = stack2[top2--];
printf("%d ", node->val);
}
}
```
4. 遍历序列
使用上述非递归遍历算法,得到的遍历序列如下:
- 中序遍历: 2 1 4 3 5
- 后序遍历: 2 4 5 3 1
阅读全文