从这篇文章开始介绍非线性结构的存储及相关操作。本文介绍二叉树的顺序存储,即用一组连续的存储空间存储二叉树,可以理解为用数组存二叉树的数据哈。相关操作包括了对二叉树的前序(先序)、中序、后序遍历,需要用到递归的算法思想进行操作,话不多说,我们开始操作:
先定义一下宏:
#define TREE_TYPE char
#define EMPTY '#'
先写一下顺序二叉树的基本结构,包含了要插入到二叉树数组的首地址以及二叉树的容量
typedef struct BinTree
{
TREE_TYPE *arr;
size_t cap;
}BinTree;
构建
//构建
BinTree *create_tree(TREE_TYPE *arr,size_t len)
{
BinTree *tree=malloc(sizeof(BinTree));
tree->arr=malloc(sizeof(TREE_TYPE)*len);
memcpy(tree->arr,arr,len*sizeof(TREE_TYPE));
tree->cap=len;
return tree;
}
销毁
//销毁
void destroy_tree(BinTree *tree)
{
free(tree->arr);
free(tree);
}
先序
//先序
void preorder_tree(BinTree *tree,int index)
{
if (index < 0 || index>tree->cap ||tree->arr[index] == '\0') return;
printf("%c",tree->arr[index]);
preorder_tree(tree,2*index+1);
preorder_tree(tree,2*index+2);
}
中序
//中序
void midorder_tree(BinTree *tree,int index)
{
if (index < 0 || index>tree->cap ||tree->arr[index] == '\0') return;
midorder_tree(tree,2*index+1);
printf("%c",tree->arr[index]);
midorder_tree(tree,2*index+2);
}
后序
//后序
void postorder_tree(BinTree *tree,int index)
{
if (index < 0 || index>tree->cap ||tree->arr[index] == '\0') return;
postorder_tree(tree,2*index+1);
postorder_tree(tree,2*index+2);
printf("%c",tree->arr[index]);
}
树的高度
//树的高度
int height_tree(BinTree *tree)
{
int i=tree->cap-1;
while(tree->arr[i]==EMPTY && i>=0) i--;
return log2(i+1)+1;
}
树的密度
//树的密度
int num_tree(BinTree *tree,int index)
{
if (index < 0 || index>tree->cap ||tree->arr[index] == '\0') return -1;
static int num=0;
num++;
num_tree(tree,2*index+1);
num_tree(tree,2*index+2);
return num;
}
插入
//插入
bool insert_tree(BinTree *tree,int index,TREE_TYPE data)
{
if(tree->arr[index]!=EMPTY) return false;
tree->arr[index]=data;
return true;
}
删除(只删除叶子结点),这里只删除叶子结点,因为还没讲到排序树,如果删除中间的结点没有特定的规则进行承上启下的连接,所以暂时只删除叶子
//删除 只删除叶子结点
bool delete_tree(BinTree *tree,int index)
{
//if((tree->arr[2*index+1]!=EMPTY && tree->arr[2*index+2]!=EMPTY)||(2*index<=tree->cap&&2*index+2<=tree->cap-1)) return false;
tree->arr[index]=EMPTY;
return true;
}
求左子树
//求左子树
int left_tree(BinTree *tree,int index)
{
if((tree->arr[2*index+1]==EMPTY && tree->arr[2*index+2]==EMPTY)||(2*index>tree->cap&&2*index+2>tree->cap-1)) return -1;
return 2*index+1;
}
求右子树
//求右子树
int right_tree(BinTree *tree,int index)
{
if((tree->arr[2*index+1]==EMPTY && tree->arr[2*index+2]==EMPTY)||(2*index>tree->cap&&2*index+2>tree->cap-1)) return -1;
return 2*index+2;
}
求根
//求根
int root_tree()
{
return 0;
}
顺序存储二叉树的操作大概就这么多,如有漏的欢迎补缺
over