#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
char data;
struct node *lchild, *rchild;
}Bitnode, *Bitree;
void Preorder(Bitree BT);
int Creat(Bitree &BT);
void Countleaves(Bitree BT, int &count);
Bitree Find(Bitree BT,char ch);
void Path(Bitree BT,Bitree s);
int main()
{
int count = 0;
Bitree BT,p;
char c;
Creat(BT);
Preorder(BT);
Countleaves(BT, count);
printf("%d\n",count);
getchar();
scanf("%c",&c);
p=Find(BT,c);
Path(BT,p);
return 0;
}
//创建二叉树
int Creat(Bitree &BT)
{
char ch;
scanf("%c", &ch);
if (ch == ' ')
BT=NULL;
else
{
BT= (Bitree)malloc(sizeof(Bitnode));
if (BT== NULL)
exit(-1);
else
{
BT->data = ch;
Creat(BT->lchild);
Creat(BT->rchild);
}
}
return 1;
}
//先序遍历(非递归)
void Preorder(Bitree BT)
{
Bitree Stack[1000];
Bitree p;
int top;
if (BT != NULL)
{
top = 1;
Stack[top] = BT;
while (top > 0)
{
p = Stack[top];
printf("%c", p->data);
top--;
if (p->rchild != NULL)
{
top++;
Stack[top] = p->rchild;
}
if (p->lchild != NULL)
{
top++;
Stack[top] = p->lchild;
}
}
}
}
void Countleaves(Bitree BT, int &count)
{
if (BT)
{
if (BT->lchild == NULL && BT->rchild == NULL)
{
count++;
}
Countleaves(BT->lchild, count);
Countleaves(BT->rchild, count);
}
}
Bitree Find(Bitree BT,char ch)
{
Bitree p;
if(BT==NULL)
return NULL;
else if(BT->data==ch)
return BT;
else
{
p=Find(BT->lchild,ch);
if(p!=NULL)
return p;
else
return Find(BT->rchild,ch);
}
}
void Path(Bitree BT,Bitree s)
{
Bitree Stack[100],p;
int tag[100];
int top = 0, i;
p = BT;
do
{
while (p != NULL)
{
top++;
Stack[top] = p;
tag[top] = 0;
p = p->lchild;
}
if (top > 0)
{
if (tag[top] == 1)
{
if (Stack[top] == s)
{
printf("路径:");
for (i = 1; i <= top; i++)
{
printf("%c ", Stack[i]->data);
}
printf("\n");
break;
}
top--;
}
else
{
p = Stack[top];
if(top>0)
{
p = p->rchild;
tag[top] = 1;
}
}
}
} while (p != NULL || top > 0);
}
二叉树的创建,排序,求叶子结点个数等
最新推荐文章于 2021-03-23 22:25:30 发布