#include<stdio.h>
#include<stdlib.h>
#define M 50
typedef struct Tree {
int data;
struct Tree* LChild;
struct Tree* RChild;
}Tree, * BitTree;
BitTree createTree() {
int data, t;
scanf_s("%d", &data);
t = getchar();
if (data == -1) { //输入-1表示NULL
return NULL;
}
else {
BitTree node = (BitTree)malloc(sizeof(Tree));
node->data = data;
printf("请输入%d左子树:", data);
node->LChild = createTree();
printf("请输入%d右子树:", data);
node->RChild = createTree();
return node;
}
}
//先序、中序、后序递归遍历
void Preorder(BitTree T) {
if (T == NULL) {
return;
}
printf("%d ", T->data);
Preorder(T->LChild);
Preorder(T->RChild);
}
void Inorder(BitTree T) {
if (T == NULL)
{
return;
}
Inorder(T->LChild);
printf("%d ", T->data);
Inorder(T->RChild);
}
void Postorder(BitTree T) {
if (T == NULL) {
return;
}
Postorder(T->LChild);
Postorder(T->RChild);
printf("%d ", T->data);
}
//层次遍历
void LAYERorder(BitTree T) {
BitTree Q[M], p;
int front, rear;
if (T != NULL) {
Q[0] = T;//根节点入队头
front = -1;
rear = 0;
while (front < rear) {//rear上升速度大于front
p = Q[++front];//一次循环输出一次
printf("%d ", p->data);
//若三层只要两次就入队完成
if (p->LChild != NULL) {
Q[++rear] = p->LChild;
}
if (p->RChild != NULL) {
Q[++rear] = p->RChild;
}
}
}
}
//先序、中序、后序非递归遍历
void PREORDER(BitTree T) {
BitTree Stack[M], p = T;
int top = -1;
if (T != NULL) {
while (p != NULL || top != -1) {
while (p != NULL) {//左进
Stack[++top] = p;
printf("%d ", p->data);//进栈顺序就是先序遍历顺序
p = p->LChild;
}
p = Stack[top--];//记录当前栈,再退一栈
p = p->RChild;
}
}
}
void INORDER(BitTree T) {
BitTree Stack[M], p = T;
int top = -1;
if (T != NULL) {
while (p != NULL || top != -1) {
while (p != NULL) {
Stack[++top] = p;
p = p->LChild;
}
p = Stack[top--];
printf("%d ", p->data);
p = p->RChild;
}
}
}
void POSTORDER(BitTree T) {
BitTree stack1[M], p = T;
int stack2[M];
int flag, top = -1;
if (T != NULL) {
while (p != NULL || top != -1) {
while (p != NULL) {
stack1[++top] = p;
stack2[top] = 0;//先把节点标记为0
p = p->LChild;
}
p = stack1[top];r
flag = stack2[top--];//出栈
if (flag == 0) {
stack1[++top] = p;
stack2[top] = 1;//再标记为1,然后到出栈
p = p->RChild;
}
else {
printf("%d ", p->data);//输出标记为1的节点
p = NULL;
}
}
}
}
c++ 树(Tree)的实现
最新推荐文章于 2025-04-27 10:13:29 发布
本文详细介绍了如何使用C++编程语言来实现树这种数据结构,涵盖了节点定义、插入、删除及遍历等基本操作。通过实例代码解析,帮助读者理解树的底层逻辑和操作方法。
2412

被折叠的 条评论
为什么被折叠?



