利用先序序列非递归程序建立二叉树,并输出先序、中序和后序序列,使用c语言
时间: 2024-05-04 09:02:24 浏览: 98
以下是利用先序序列非递归程序建立二叉树,并输出先序、中序和后序序列的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结构体
typedef struct TreeNode {
char data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 定义栈结构体
typedef struct StackNode {
TreeNode *node;
struct StackNode *next;
} StackNode;
// 初始化栈
void initStack(StackNode **stack) {
*stack = NULL;
}
// 判断栈是否为空
int isStackEmpty(StackNode *stack) {
return stack == NULL ? 1 : 0;
}
// 入栈
void push(StackNode **stack, TreeNode *node) {
StackNode *newNode = (StackNode*)malloc(sizeof(StackNode));
newNode->node = node;
newNode->next = *stack;
*stack = newNode;
}
// 出栈
TreeNode* pop(StackNode **stack) {
if (isStackEmpty(*stack)) {
return NULL;
}
TreeNode *node = (*stack)->node;
StackNode *temp = *stack;
*stack = (*stack)->next;
free(temp);
return node;
}
// 先序遍历二叉树
void preOrder(TreeNode *root) {
if (root == NULL) {
return;
}
printf("%c ", root->data);
preOrder(root->left);
preOrder(root->right);
}
// 中序遍历二叉树
void inOrder(TreeNode *root) {
if (root == NULL) {
return;
}
inOrder(root->left);
printf("%c ", root->data);
inOrder(root->right);
}
// 后序遍历二叉树
void postOrder(TreeNode *root) {
if (root == NULL) {
return;
}
postOrder(root->left);
postOrder(root->right);
printf("%c ", root->data);
}
// 建立二叉树
TreeNode* createBinaryTree(char preOrder[], int size) {
StackNode *stack;
initStack(&stack);
TreeNode *root = (TreeNode*)malloc(sizeof(TreeNode));
root->data = preOrder[0];
root->left = NULL;
root->right = NULL;
push(&stack, root);
int i = 1;
while (i < size) {
TreeNode *current = (TreeNode*)malloc(sizeof(TreeNode));
current->data = preOrder[i];
current->left = NULL;
current->right = NULL;
if (preOrder[i] == '#') {
TreeNode *parent = pop(&stack);
while (!isStackEmpty(stack) && parent->right != NULL) {
parent = pop(&stack);
}
if (parent->right == NULL) {
parent->right = current;
} else {
printf("Invalid input!\n");
return root;
}
} else {
TreeNode *parent = peek(stack);
if (parent == NULL) {
printf("Invalid input!\n");
return root;
}
if (parent->left == NULL) {
parent->left = current;
} else {
parent = pop(&stack);
while (!isStackEmpty(stack) && parent->right != NULL) {
parent = pop(&stack);
}
if (parent->right == NULL) {
parent->right = current;
} else {
printf("Invalid input!\n");
return root;
}
}
push(&stack, current);
}
i++;
}
return root;
}
// 获取栈顶元素
TreeNode* peek(StackNode *stack) {
if (isStackEmpty(stack)) {
return NULL;
}
return stack->node;
}
int main() {
char preOrder[] = {'A', 'B', 'D', '#', '#', 'E', '#', '#', 'C', 'F', '#', '#', 'G', '#', '#'};
int size = sizeof(preOrder) / sizeof(preOrder[0]);
TreeNode *root = createBinaryTree(preOrder, size);
printf("PreOrder: ");
preOrder(root);
printf("\n");
printf("InOrder: ");
inOrder(root);
printf("\n");
printf("PostOrder: ");
postOrder(root);
printf("\n");
return 0;
}
```
输入先序序列(例如:ABD##E##CF##G##),程序会依次建立二叉树并输出先序、中序和后序序列。
阅读全文