二叉树的小程序

没事做,写了个二叉树的小程序,供初学者看看
#include<iostream>
using namespace std;
#define defeated NULL

struct Tree
{
	char ele;
	Tree *lchild;
	Tree *rchild;
};
Tree *create()
{
	char ch;
	cin>>ch;
	if(ch=='#')
	{
		return NULL;
	}
	else
	{
		Tree *root=(Tree*)malloc(sizeof(Tree));
		root->ele=ch;
		root->lchild=create();
			root->rchild=create();
			return root;
	}
}

void visit(Tree *t)
{
	cout<<t->ele<<" ";
}
void preOrder(Tree * t )
{
	if(t!=NULL)
	{
		visit(t);
		preOrder(t->lchild);
		preOrder(t->rchild);
	}
}
int size(Tree *t)
{
	if(t==NULL)
 return 0;
	else return 1+size(t->lchild)+size(t->rchild);

}
int sizeOfLeaves(Tree *t)
{
	if(t==NULL)  return 0;
	else if(t->lchild==NULL&&t->rchild==NULL) return 1;
	else return sizeOfLeaves(t->lchild)+sizeOfLeaves(t->rchild);
}
int depth(Tree *t)
{
	int h1,h2,h;
	if(t!=NULL)
	{
		h1=depth(t->lchild);
		h2=depth(t->rchild);
		h=h1>h2?h1:h2;
		return h+1;
	}
	return 0;
}

int main()
{
 cout<<"---\t Weclome to binary Tree!-----\t\n";
 Tree *p;
 p=create();
 cout<<"Select the function please! \n";
 cout<<"1 遍历这棵树\n";
 cout<<"2 查找节点个数\n";
 cout<<"3 叶子结点个数\n";
 cout<<"4 树的深度\n";
 int sizeOfTree=size(p);
 int leaves=sizeOfLeaves(p);
 int d=depth(p);
 int k=0;
 cout<<"begin scan& use?(1 for yes)\n";
 cin>>k;
 while(k)
 {
 int option;
 cin>>option;
 switch(option)
 {
 case 1: preOrder(p);
	 cout<<'\n';
	 break;
 case 2: cout<<"结点个数为: "<<sizeOfTree<<'\n';break;
 case 3: cout<<"叶子结点个数为: "<<leaves<<'\n';break;
 case 4: cout<<"树的深度为:  "<<d<<'\n';break;
 default: cout<<"Unknown Error!";
 }
 cout<<"继续或结束?(1 for yes)\n";
 cin>>k;
 if(k==1) system("cls");
 cout<<"Select the function please! \n";
 cout<<"1 遍历这棵树\n";
 cout<<"2 查找节点个数\n";
 cout<<"3 叶子结点个数\n";
 cout<<"4 树的深度\n";

 }
 return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值