请C语言编程实现二叉树中序遍历和后续遍历的递归算法和非递归算法。
时间: 2024-05-07 18:19:14 浏览: 113
递归算法:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 中序遍历递归算法
void inorder_recursive(TreeNode *root) {
if (root == NULL) return;
inorder_recursive(root->left);
printf("%d ", root->data);
inorder_recursive(root->right);
}
// 后序遍历递归算法
void postorder_recursive(TreeNode *root) {
if (root == NULL) return;
postorder_recursive(root->left);
postorder_recursive(root->right);
printf("%d ", root->data);
}
int main() {
// 构建二叉树
TreeNode *root = (TreeNode *) malloc(sizeof(TreeNode));
root->data = 1;
root->left = (TreeNode *) malloc(sizeof(TreeNode));
root->left->data = 2;
root->left->left = NULL;
root->left->right = NULL;
root->right = (TreeNode *) malloc(sizeof(TreeNode));
root->right->data = 3;
root->right->left = NULL;
root->right->right = NULL;
root->left->right = (TreeNode *) malloc(sizeof(TreeNode));
root->left->right->data = 4;
root->left->right->left = NULL;
root->left->right->right = NULL;
printf("中序遍历结果:");
inorder_recursive(root);
printf("\n后序遍历结果:");
postorder_recursive(root);
return 0;
}
```
非递归算法:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 中序遍历非递归算法
void inorder_nonrecursive(TreeNode *root) {
if (root == NULL) return;
TreeNode *stack[100];
int top = -1;
while (root != NULL || top != -1) {
while (root != NULL) {
stack[++top] = root;
root = root->left;
}
root = stack[top--];
printf("%d ", root->data);
root = root->right;
}
}
// 后序遍历非递归算法
void postorder_nonrecursive(TreeNode *root) {
if (root == NULL) return;
TreeNode *stack[100];
int top = -1;
TreeNode *last_visited = NULL;
while (root != NULL || top != -1) {
while (root != NULL) {
stack[++top] = root;
root = root->left;
}
root = stack[top];
if (root->right == NULL || root->right == last_visited) {
printf("%d ", root->data);
last_visited = root;
root = NULL;
--top;
} else {
root = root->right;
}
}
}
int main() {
// 构建二叉树
TreeNode *root = (TreeNode *) malloc(sizeof(TreeNode));
root->data = 1;
root->left = (TreeNode *) malloc(sizeof(TreeNode));
root->left->data = 2;
root->left->left = NULL;
root->left->right = NULL;
root->right = (TreeNode *) malloc(sizeof(TreeNode));
root->right->data = 3;
root->right->left = NULL;
root->right->right = NULL;
root->left->right = (TreeNode *) malloc(sizeof(TreeNode));
root->left->right->data = 4;
root->left->right->left = NULL;
root->left->right->right = NULL;
printf("中序遍历结果:");
inorder_nonrecursive(root);
printf("\n后序遍历结果:");
postorder_nonrecursive(root);
return 0;
}
```
阅读全文