请用c语言实现二叉树中序遍历和后续遍历的递归算法和非递归算法。
时间: 2024-05-16 22:14:42 浏览: 102
以下是二叉树中序遍历和后续遍历的递归算法和非递归算法的 C 语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
// 递归中序遍历
void inorderTraversalRecursive(struct TreeNode* root) {
if (root == NULL) return;
inorderTraversalRecursive(root->left);
printf("%d ", root->val);
inorderTraversalRecursive(root->right);
}
// 递归后续遍历
void postorderTraversalRecursive(struct TreeNode* root) {
if (root == NULL) return;
postorderTraversalRecursive(root->left);
postorderTraversalRecursive(root->right);
printf("%d ", root->val);
}
// 非递归中序遍历
void inorderTraversalNonRecursive(struct TreeNode* root) {
struct TreeNode* stack[100];
int top = -1;
while (root || top != -1) {
while (root) {
stack[++top] = root;
root = root->left;
}
root = stack[top--];
printf("%d ", root->val);
root = root->right;
}
}
// 非递归后续遍历
void postorderTraversalNonRecursive(struct TreeNode* root) {
struct TreeNode* stack[100];
int top = -1;
struct TreeNode* lastVisit = NULL;
while (root || top != -1) {
while (root) {
stack[++top] = root;
root = root->left;
}
root = stack[top];
if (root->right == NULL || root->right == lastVisit) {
printf("%d ", root->val);
lastVisit = root;
root = NULL;
top--;
} else {
root = root->right;
}
}
}
int main() {
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->left->left = NULL;
root->left->right = NULL;
root->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->val = 3;
root->right->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->left->val = 4;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->right->val = 5;
root->right->right->left = NULL;
root->right->right->right = NULL;
printf("递归中序遍历: ");
inorderTraversalRecursive(root);
printf("\n");
printf("递归后续遍历: ");
postorderTraversalRecursive(root);
printf("\n");
printf("非递归中序遍历: ");
inorderTraversalNonRecursive(root);
printf("\n");
printf("非递归后续遍历: ");
postorderTraversalNonRecursive(root);
printf("\n");
return 0;
}
```
输出结果如下:
```
递归中序遍历: 2 1 4 3 5
递归后续遍历: 2 4 5 3 1
非递归中序遍历: 2 1 4 3 5
非递归后续遍历: 2 4 5 3 1
```
阅读全文