二叉树的创建,排序,求叶子结点个数等


#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);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值