一、二叉树的存储结构
//二叉树 //二叉树的链式存储
typedef struct BiTNode{
TElemType data;
struct BiTNode *lchild, *rchild;//左右孩子的节点
}BiTNode, *BiTree;
二、二叉树的创建和打印
int strIndex = 0;
Status CreateBiTree(BiTree &T, char *preStr){
//递归创建二叉树 先序遍历的字符串 index索引到的字符串序列
int ch = preStr[strIndex++];
if (ch == '#')
{
//当前结点为空节点
T = NULL;
}
else
{
//当前结点不为空
T = (BiTree)malloc(sizeof(BiTNode));
if (T == NULL)
{
printf("空间分配失败");
return OVERFLOW;
}
T->data = ch;
CreateBiTree(T->lchild,preStr);
CreateBiTree(T->rchild,preStr);
}
return OK;
}
//打印
void PrintTree_L(BiTree &T, int n){
if (T == NULL)return;
PrintTree_L(T->rchild, n + 3);
for (int i = 0; i < n; i++){
printf(" ");
}
printf("%c\n", T->data);
PrintTree_L(T->lchild, n + 3);
return;
}
Status PrintElement(TElemType e){
printf("%c",e);
return OK;
}
void main(){
char * preStr = "ABC##DE#G##F###";//先序遍历字符串
BiTree tree;
CreateBiTree(tree,preStr);
PrintTree_L(tree,0);
}
输出:A
F
D
G
E
B
C
请按任意键继续. . .
三、二叉树的改进,线索二叉树
在一棵二叉树中有n个结点就有n+1个空链域,为了好好利用这些空间,于是在二叉树上进行的改进,空链域中,如果是左孩子,则指示前驱,否则就是后继。有了这种改进主要还是在先序遍历中起到了很好的效率。至于如何构造这棵树,我也不会,这里就不误人子弟了。