// 二叉树.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include"stdlib.h"
#include"string.h"
#include"conio.h"
typedef struct node
{
char data;
struct node* lc;
struct node* rc;
}MYTREE, * PMYTREE;
void preorder(PMYTREE root, char* out);
void inorder(PMYTREE root, char* out);
void postorder(PMYTREE root, char* out);
void levelorder(PMYTREE root, char* out);
int main()
{
PMYTREE root = NULL;
PMYTREE s;
PMYTREE Q[128];
int front = 1, rear = 0;
char temp[128], * p;
printf("请按照完全二叉树格式输入节点,空间用@代替,逗号间隔:");
scanf_s("%s", temp, 128);
p = temp;
while (strlen(p) > 0)
{
s = NULL;
if (*p != '@')
{
s = (PMYTREE)malloc(sizeof(MYTREE));
s->data = *p;
s->lc = NULL;
s->rc = NULL;
}
rear++;
Q[rear] = s;
if (rear == 1)
root = s;
else
{
if (s != NULL && Q[front] != NULL)
{
if (rear % 2 == 0)
Q[front]->lc = s;
else
Q[front]->rc = s;
}
if (rear % 2 == 1)
front++;
}
if (strlen(p) > 1)
p = p + 2;
else
p = p + 1;
}
printf("二叉树已经成功创建\r\n");
memset(temp, 0, 128);
preorder(root, temp);
printf("先序遍历结果为:%s\r\n", temp);
memset(temp, 0, 128);
inorder(root, temp);
printf("中序遍历结果为:%s\r\n", temp);
memset(temp, 0, 128);
postorder(root, temp);
printf("后序遍历结果为:%s\r\n", temp);
memset(temp, 0, 128);
levelorder(root, temp);
printf("层次遍历结果为:%s\r\n", temp);
return 0;
}
void preorder(PMYTREE root, char* out)//先序遍历
{
if (root != NULL)
{
sprintf(out, "%s%c", out, root->data);
preorder(root->lc, out);
preorder(root->rc, out);
}
}
void inorder(PMYTREE root, char* out)//中序遍历
{
if (root != NULL)
{
inorder(root->lc, out);
sprintf(out, "%s%c", out, root->data);
inorder(root->rc, out);
}
}
void postorder(PMYTREE root, char* out)//后序遍历
{
if (root != NULL)
{
postorder(root->lc, out);
postorder(root->rc, out);
sprintf(out, "%s%c", out, root->data);
}
}
void levelorder(PMYTREE root, char* out)//层次遍历
{
PMYTREE Q[128], s;
int front = 0, rear = 0;
Q[rear++] = root;
while (rear > front)
{
printf(out, "%s%c", out, Q[front]->data);
s = Q[front++];
if (s->lc != NULL)
Q[rear++] = s->lc;
if (s->rc != NULL)
Q[rear++] = s->rc;
}
}
2021-11-06
最新推荐文章于 2025-07-22 16:29:43 发布