#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct BTNode
{
char data;
struct BTNode *lChild;
struct BTNode *rChild;
} BTNODE, *BTREE;
BTREE create();
void preOrder(BTREE);
void inOrder(BTREE);
void postOrder(BTREE);
void preOrder1(BTREE);
void inOrder1(BTREE);
void postOrder1(BTREE);
int main(void)
{
printf("请输入根结点:");
BTREE bt = create();
printf("\n先序遍历为:");
preOrder(bt);
printf("\n中序遍历为:");
inOrder(bt);
printf("\n后序遍历为:");
postOrder(bt);
return 0;
}
BTREE create()
{
int val;
scanf("%d", &val);
if (val <= 0)
{
return NULL;
}
BTREE bt = (BTREE)malloc(sizeof(BTNODE));
if (!bt)
{
printf("创建失败\n");
}
bt->data = val;
printf("请输入%d的左孩子结点:", val);
bt->lChild = create();
printf("请输入%d的右孩子结点:", val);
bt->rChild = create();
return bt;
}
void preOrder(BTREE bt)
{
if (bt == NULL)
{
return;
}
printf("%d ", bt->data);
preOrder(bt->lChild);
preOrder(bt->rChild);
}
void inOrder(BTREE bt)
{
if (bt == NULL)
{
return;
}
inOrder(bt->lChild);
printf("%d ", bt->data);
inOrder(bt->rChild);
}
void postOrder(BTREE bt)
{
if (bt == NULL)
{
return;
}
postOrder(bt->lChild);
postOrder(bt->rChild);
printf("%d ", bt->data);
}
//非递归方式遍历
void preOrder1(BTREE bt)
{
BTREE stack[15];
int top = -1;
BTREE root = bt;
while (root != NULL || top != -1)
{
if (root != NULL)
{
stack[++top] = root;
printf("%d ", root->data);
root = root->lChild;
}
else
{
root = stack[top--];
root = root->rChild;
}
}
}
void inOrder1(BTREE bt)
{
BTREE stack[15];
int top = -1;
BTREE root = bt;
while (root != NULL || top != -1)
{
if (root != NULL)
{
stack[++top] = root;
root = root->lChild;
}
else
{
root = stack[top--];
printf("%d ", root->data);
root = root->rChild;
}
}
}
void postOrder1(BTREE bt)
{
BTREE stack[15];
BTREE stack1[15];
int top = -1;
int i = -1;
BTREE root = bt;
stack[++top] = root;
while (top != -1)
{
root = stack[top--];
stack1[++i] = root;
if (root->lChild != NULL)
{
stack[++top] = root->lChild;
}
if (root->rChild != NULL)
{
stack[++top] = root->rChild;
}
}
while (i != -1)
{
printf("%d ", stack1[i--]->data);
}
}
C语言二叉树操作
最新推荐文章于 2024-09-16 18:31:59 发布