结合链表的尾插法、前序打印法、二级指针偏移等知识点,将输入的字符串内容存放到满二叉树数据结构体中,然后用前序打印出结果。
关键思想:链表辅助,定位二叉树节点位置存放输入的内容。
运行效果:
完整示例代码:
#include <stdio.h>
#include <stdlib.h>
typedef char ElemType;
typedef struct BinaryTree
{
char c;
struct BinaryTree *left;
struct BinaryTree *right;
}Tree, *pTree;
typedef struct LinkList
{
pTree pInsert;
struct LinkList *pNext;
}Link, *pLink;
//层次建树法、尾插法、辅助链条法
void BuildBinaryTree(pTree *ppTreeRoot, pLink *pphead, pLink *pptail, ElemType val)
{
pTree pTreeNew=(pTree)calloc(1,sizeof(Tree));
pLink pLinkNew=(pLink)calloc(1,sizeof(Link));
pLink pLinkCur=*pphead;
pTreeNew->c=val;
pLinkNew->pInsert=pTreeNew;
if (NULL==*ppTreeRoot)
{
*ppTreeRoot=pTreeNew;
*pphead=pLinkNew;
*pptail=pLinkNew;
}else
{
//尾插法
(*pptail)->pNext=pLinkNew;
*pptail=pLinkNew;
//判断当前辅助链节点对应的树的左右节点是否为空
if (NULL==pLinkCur->pInsert->left)
{
pLinkCur->pInsert->left=pTreeNew;
}else if (NULL==pLinkCur->pInsert->right)
{
pLinkCur->pInsert->right=pTreeNew;
//易错点:树节点满,头指针后移
*pphead=pLinkCur->pNext;
//易错点:注意要释放pLinkCur并NULL
free(pLinkCur);
pLinkCur=NULL;
}
}
}
//前序打印方式
void preOrder(pTree p)
{
if (NULL!=p)
{
putchar(p->c);
preOrder(p->left);
preOrder(p->right);
}
}
int main()
{
ElemType val;
pTree pTreeRoot=NULL;
pLink phead=NULL,ptail=NULL;
printf("请输入内容,将存放在二叉树中:\n");
while (scanf("%c", &val)!=EOF)
{
if (val=='\n')
{
break;
}
BuildBinaryTree(&pTreeRoot, &phead, &ptail, val);
}
printf("二叉树中存放的内容:\n");
preOrder(pTreeRoot);
printf("\n");
system("pause");
return 0;
}