作业

#include<iostream>
using namespace std;
struct Node
{
	char data;
	Node *l,*r;
};
int get(int x)
{
	return (x+1)/2;
}
void build(Node *t,int l,int r)
{
	
//	char c;
	cout<<"请输入所在节点的元素 若为空 则输入'#':";
	cin>>t->data;
	if(l==r) 
	{
		t->l=NULL;
		t->r=NULL;
		return ;
	}
	t->l=new (Node);
	build(t->l,l,(l+r)/2);
	t->r=new (Node);
	build(t->r,(l+r)/2+1,r);
}
void Traq(Node *t)
{
	cout<<t->data<<" ";
	if(t->l)
		Traq(t->l);
	if(t->r)
		Traq(t->r);
}
void Traz(Node *t)
{
	if(t->l)
		Traz(t->l);
	cout<<t->data<<" ";	
	if(t->r)
		Traz(t->r);
}
void Trah(Node *t)
{
	if(t->l)
		Trah(t->l);
	if(t->r)
		Trah(t->r);
	cout<<t->data<<" ";	
}
int FNd(Node *t)
{
	if(t->data=='#') return 0;
	if(t->l==NULL&&t->r==NULL)
		return 1;
	return FNd(t->l)+FNd(t->r)+1;
}
int max(int x,int y)
{
	if(x>y) return x;
	return y;
}
int FH(Node *t)
{
	if(t->data=='#')
		return 0;
	if(t->l==NULL&&t->r==NULL)
		return 1;
	return  max(FH(t->l),FH(t->r))+1;
}
void frr(Node *t)
{
	if(t->l==NULL&&t->r==NULL)
	{
		free(t);
		return ;
	}
	frr(t->l);
	frr(t->r);
	free(t);
}
int main()
{
	int cas,n,x;
	Node *root;
	root=new (Node);
	cout<<"0:结束操作"<<endl;
	cout<<"1:建树"<<endl;
	cout<<"2:前序列遍历树"<<endl;
	cout<<"3:中序列遍历树"<<endl;
	cout<<"4:后序列遍历树"<<endl;
	cout<<"5:求二叉树的节点数(有具体元素的节点)"<<endl;
	cout<<"6:求二叉树的高度(有具体元素的)"<<endl;
	while(cin>>cas)
	{
		if(cas==0) break;
		switch(cas){
		case 1:cout<<"请输入所建二叉树所在满二叉树有多少节点";cin>>x;n=get(x);build(root,1,n);break;
        case 2:cout<<"前序遍历结果为:";Traq(root);cout<<endl;break;
		case 3:cout<<"中序遍历结果为:";Traz(root);cout<<endl;break;
		case 4:cout<<"后序遍历结果为:";Trah(root);cout<<endl;break;
		case 5:cout<<"有"<<FNd(root)<<"个节点"<<endl;break;
		case 6:cout<<"高度为"<<FH(root)<<endl;break;
		}
	}
	frr(root);
	return 0;
}


 

posted @ 2014-05-28 19:03  _一千零一夜  阅读(200)  评论(0编辑  收藏  举报