二叉树遍历的应用(求叶结点的数量和树的深度)

#include<stdio.h>	
#include<stdlib.h>
#include <iostream>
using namespace std;
#define MAXSIZE 10
typedef struct node
{
	char data;
	struct node* lchild, * rchild;
}BSTree;
void Preorder(BSTree* p)
{
	if (p != NULL)
	{
		cout << p->data;
		Preorder(p->lchild);
		Preorder(p->rchild);
	}
}
BSTree* Search(BSTree* p, char x)//非递归中序遍历查找数据x
{
	BSTree* stack[MAXSIZE];
	int i = 0;
	stack[0] = NULL;
	while (i>=0)
	{
		if (p!=NULL)
		{
			if (p->data==x)
			{
				return	p;
			}
			else
			{
				stack[++i] = p;
				p = p->lchild;
			}
		
		}
		else
		{
			p = stack[i--];
			p = p->rchild;
		}
		if (p == NULL && i == 0)
			break;
	}
	return NULL;
}
int Depth(BSTree* p)//后序遍历二叉树的深度
{
	int lchild, rchild;
	if (p==NULL)
	{
		return 0;
	}
	else
	{
		lchild = Depth(p->lchild);
		rchild = Depth(p->rchild);
		return lchild > rchild ? (lchild + 1) : (rchild + 1);
	}
}
int CountLeaf(BSTree* p)//叶节点的数量
{
	if (p == NULL)
		return 0;
	if (p->rchild == NULL && p->lchild == NULL)
		return 1;
	return(CountLeaf(p->lchild) + CountLeaf(p->rchild));
}
void Create(BSTree** p)
{
	char ch;
	scanf_s("%c", &ch);
	if (ch!='.')
	{
		*p = (BSTree*)malloc(sizeof(BSTree));
		(*p)->data = ch;
		Create(&(*p)->lchild);
		Create(&(*p)->rchild);
	}
	else
	{
		*p = NULL;
	}
}
int main()
{
	BSTree* root, * p;
	char x;
	printf("创建二叉树");
	Create(&root);
	printf("pre遍历");
	Preorder(root);
	cout << endl;
	getchar();
	printf("输入要查找的二叉树结点信息");
	scanf_s("%c", &x);
	p = Search(root, x);
	if (p==NULL)
	{
		cout << "no found" << endl;
	}
	else
	{
		cout << "element is" << p->data << endl;
	}
	cout << CountLeaf(root) << endl;
	cout << Depth(root) << endl;
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值