最近在复习数据结构,顺便看看大一的时候写的代码,看完之后比当初有了更加深刻的体会。
希望这些能提供给初学者一些参考。
//建立二叉树的二叉链表存储结构 (先序)
void CreateBinTree(BinTree *root)
{
char c;
if('#'==(c=getchar()))
*root=NULL;
else
{
*root=(BTNode*)malloc(sizeof(BTNode));
(*root)->data=c;
CreateBinTree(&((*root)->lchild));
CreateBinTree(&((*root)->rchild));
}
}
//求二叉树的叶子节点的个数 方法1
int CountLeaf(BinTree root)
{
int static leaf=0;
if(root!=NULL)
{
CountLeaf(root->lchild);
if(root->lchild==NULL && root->rchild==NULL)
++leaf;
CountLeaf(root->rchild);
}
return leaf;
}
//求二叉树的叶子节点的个数 方法2
int CountLeaf(BinTree root)
{
if(NULL==root)
return 0;
else if(NULL==root->lchild && NULL==root->rchild)
return 1;
return (CountLeaf(root->lchild)+CountLeaf(root->rchild));
}
//设计一个算法,在二叉树中求在 先序序列 中处于第k个位置的结点
count=0;
BinTree search(BinTree root, int k)
{
BinTree p;
if(root==NULL)
return NULL;
else
{
if(++count==k)
return root;
else
{
p=search(root->lchild,k);
if(p)
return p;
p=search(root->rchild,k);
}
}
}
//设计一个算法,在二叉树中求在 先序序列 中值为x的结点
BinTree LocateTree(BinTree root, elemtype x)
{
BinTree p;
if(NULL==root)
return NULL;
else if(x==root->data)
return root;
else
{
p=LocateTree(root->lchild,x);
if(p)
return p;
p=LocateTree(root->lchild,x);
}
}