1. 遍历
b站收藏夹
2. 二叉树的存储
2.1 顺序存储
Linear_Tree.c
不推荐使用,因为会造成空间浪费
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include<stdbool.h>
typedef bool status;
#define MAXSIZE 3
//二叉树的顺序存储
struct B_Tree
{
char tree[MAXSIZE];
};
//创建二叉树的顺序存储
struct B_Tree *Tree_Create()
{
struct B_Tree *tree1=(struct B_Tree *)malloc(sizeof(struct B_Tree));
if(tree1==NULL)
{
return false;
}
memset(tree1->tree,0,sizeof(tree1->tree));
return tree1;
}
//插入
void Tree_Insert(struct B_Tree *T ,char data)
{
for(int i=0; i<MAXSIZE;i++)
{
if(T->tree[i]==0)
{
T->tree[i]=data;
break;
}
}
}
//遍历
void Tree_Travel(struct B_Tree *T )
{
for(int i=0; i<MAXSIZE;i++)
{
if(T->tree[i]=='#')
{
continue;
}
printf("二叉树中的结点:%c\n",T->tree[i]);
}
}
int main()
{
struct B_Tree *T=Tree_Create();
Tree_Insert(T,'a');
Tree_Insert(T,'b');
Tree_Insert(T,'#');
Tree_Travel(T);
return 0;
}
2.2 链式存储
2.2.1 普通方法创建
Linear_Tree_list.c
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
struct Tree
{
char data;
struct Tree *LChild;
struct Tree *RChild;
};
struct Tree *Tree_Create(char data)
{
struct Tree*T=(struct Tree *)malloc(sizeof(struct Tree));
if(T==NULL)
{
return NULL;
}
T->data=data;
T->LChild=NULL;
T->RChild=NULL;
return T;
}
int main()
{
//非递归创建二叉树
struct Tree *T1=Tree_Create(10);
struct Tree *T2=Tree_Create(20);
T1->LChild=T2;
return 0;
}
2.2.2 递归创建
List_Tree_DiGui.c
#include "stdio.h"
#include "stdlib.h"
#include "stdbool.h"
typedef bool status;
//二叉树的链式存储--递归创建
struct Tree
{
char data;
struct Tree *LChild;
struct Tree *RChild;
};
//创建二叉树
struct Tree *Tree_Create()
{
struct Tree *T;
char in_ch;//获取用户输入的字符
scanf("%c",&in_ch);
if(in_ch=='#')
{
return NULL;
}
T=(struct Tree *)malloc(sizeof(struct Tree));
if(T==NULL)
{
printf("结点空间申请失败,创建失败!\n");
return NULL;
}
T->data=in_ch;
T->LChild=Tree_Create();
T->RChild=Tree_Create();
return T;
}
//先序遍历
status begin_Travel(struct Tree *T)
{
if(T==NULL)
{
return false;
}
printf("%c",T->data);
begin_Travel(T->LChild);
begin_Travel(T->RChild);
return true;
}
//中序遍历
status mid_Travel(struct Tree *T)
{
if(T==NULL)
{
return false;
}
mid_Travel(T->LChild);
printf("%c",T->data);
mid_Travel(T->RChild);
return true;
}
//后序遍历
status back_Travel(struct Tree *T)
{
if(T==NULL)
{
return false;
}
back_Travel(T->LChild);
back_Travel(T->RChild);
printf("%c",T->data);
return true;
}
int main()
{
struct Tree *tree=Tree_Create();
printf("先序遍历:\n");
begin_Travel(tree);
printf("\n");
printf("中序遍历:\n");
mid_Travel(tree);
printf("\n");
printf("后序遍历:\n");
back_Travel(tree);
printf("\n");
}
输入abc###c##
结果