使用c语言完成:非递归创建链表二叉树
时间: 2024-01-23 22:13:53 浏览: 97
以下是使用C语言完成非递归创建链表二叉树的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct TreeNode {
char data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
typedef struct Stack {
TreeNode *data[MAXSIZE];
int top;
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
int isEmpty(Stack *s) {
return s->top == -1;
}
int isFull(Stack *s) {
return s->top == MAXSIZE - 1;
}
void push(Stack *s, TreeNode *node) {
if (isFull(s)) {
printf("Stack is full.\n");
return;
}
s->data[++s->top] = node;
}
TreeNode *pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty.\n");
return NULL;
}
return s->data[s->top--];
}
TreeNode *createBinaryTree(char *preorder, char *inorder, int length) {
if (preorder == NULL || inorder == NULL || length <= 0) {
return NULL;
}
Stack s;
initStack(&s);
int preIndex = 0, inIndex = 0;
TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode));
root->data = preorder[preIndex];
root->left = NULL;
root->right = NULL;
TreeNode *current = root;
push(&s, current);
preIndex++;
while (preIndex < length) {
if (!isEmpty(&s) && s.data[s.top]->data == inorder[inIndex]) {
current = pop(&s);
inIndex++;
} else {
TreeNode *node = (TreeNode *)malloc(sizeof(TreeNode));
node->data = preorder[preIndex];
node->left = NULL;
node->right = NULL;
current->left = node;
current = node;
push(&s, current);
preIndex++;
}
}
return root;
}
void inorderTraversal(TreeNode *root) {
if (root == NULL) {
return;
}
Stack s;
initStack(&s);
TreeNode *current = root;
while (current != NULL || !isEmpty(&s)) {
while (current != NULL) {
push(&s, current);
current = current->left;
}
current = pop(&s);
printf("%c ", current->data);
current = current->right;
}
}
void postorderTraversal(TreeNode *root) {
if (root == NULL) {
return;
}
Stack s;
initStack(&s);
TreeNode *current = root;
TreeNode *lastVisit = NULL;
while (current != NULL || !isEmpty(&s)) {
while (current != NULL) {
push(&s, current);
current = current->left;
}
current = s.data[s.top];
if (current->right == NULL || current->right == lastVisit) {
printf("%c ", current->data);
pop(&s);
lastVisit = current;
current = NULL;
} else {
current = current->right;
}
}
}
void destroyBinaryTree(TreeNode *root) {
if (root == NULL) {
return;
}
destroyBinaryTree(root->left);
destroyBinaryTree(root->right);
free(root);
}
int main() {
char preorder[] = {'A', 'B', 'D', 'E', 'C', 'F', 'G'};
char inorder[] = {'D', 'B', 'E', 'A', 'F', 'C', 'G'};
int length = sizeof(preorder) / sizeof(preorder[0]);
TreeNode *root = createBinaryTree(preorder, inorder, length);
printf("Inorder traversal: ");
inorderTraversal(root);
printf("\nPostorder traversal: ");
postorderTraversal(root);
printf("\n");
destroyBinaryTree(root);
return 0;
}
```
阅读全文