请用C语言写出程序:输入字符序列,建立二叉树;按先序中序后序遍历二叉树(三种递归算法和中序遍历的非递归算法)
时间: 2024-05-01 16:19:06 浏览: 158
二叉树前序、中序、后序三种遍历的非递归算法(C语言)
```c
#include <stdio.h>
#include <stdlib.h>
//定义二叉树结构体
struct TreeNode {
char data;
struct TreeNode* left;
struct TreeNode* right;
};
//根据输入的字符序列建立二叉树
struct TreeNode* createBinaryTree() {
char ch;
scanf("%c", &ch);
if (ch == '#') {
return NULL;
}
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->data = ch;
root->left = createBinaryTree();
root->right = createBinaryTree();
return root;
}
//先序遍历二叉树(递归算法)
void preOrderTraversalRecursive(struct TreeNode* root) {
if (root == NULL) {
return;
}
printf("%c ", root->data);
preOrderTraversalRecursive(root->left);
preOrderTraversalRecursive(root->right);
}
//中序遍历二叉树(递归算法)
void inOrderTraversalRecursive(struct TreeNode* root) {
if (root == NULL) {
return;
}
inOrderTraversalRecursive(root->left);
printf("%c ", root->data);
inOrderTraversalRecursive(root->right);
}
//后序遍历二叉树(递归算法)
void postOrderTraversalRecursive(struct TreeNode* root) {
if (root == NULL) {
return;
}
postOrderTraversalRecursive(root->left);
postOrderTraversalRecursive(root->right);
printf("%c ", root->data);
}
//中序遍历二叉树(非递归算法)
void inOrderTraversal(struct TreeNode* root) {
struct TreeNode* stack[100];
int top = -1;
struct TreeNode* p = root;
while (p != NULL || top != -1) {
if (p != NULL) {
stack[++top] = p;
p = p->left;
} else {
p = stack[top--];
printf("%c ", p->data);
p = p->right;
}
}
}
int main() {
printf("请输入字符序列,以#表示空节点:\n");
struct TreeNode* root = createBinaryTree();
printf("先序遍历结果:");
preOrderTraversalRecursive(root);
printf("\n中序遍历结果:");
inOrderTraversalRecursive(root);
printf("\n后序遍历结果:");
postOrderTraversalRecursive(root);
printf("\n中序遍历结果(非递归算法):");
inOrderTraversal(root);
return 0;
}
```
阅读全文