⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 7_62.cpp

📁 C++程序设计技能百练随书配套光盘的源码
💻 CPP
字号:
#include<iostream.h>
#include<iomanip.h>

int list=1;  //全局变量用于输出名次
struct sport		//结构声明(声明结构时不分配内存空间)
{
	char num[4];	//数据成员1(结构中包含的数据变量称为数据成员)
	double grade;	//数据成员2
};		//不能缺少分号
struct tree
{
	sport* spt;  //指向sport结构的指针
	tree *left,*right;  //左、右子树指针
};
class Btree
{
	tree* root;
public:
	Btree(){root=NULL;}  //构造函数初始化根节点
	void creat_btree(sport*);
	void display()
	{
		cout<<"名次"<<"   "<<"编号"<<"   "<<"成绩"<<endl;
		inorder(root);
		cout<<endl;
	}
	void inorder(tree*);
};
void Btree::creat_btree(sport *x)  //建立排序二叉树
{
	tree *newnode=new tree;
	newnode->spt=x;
	newnode->left=newnode->right=NULL;
	if (root==NULL)
		root=newnode;
	else
	{
		tree* back;
		tree* current=root;
		while(current!=NULL)  //找到要插入Newnode的节点指针
		{
			back=current;
			if(current->spt->grade>x->grade)
				current=current->left;
			else
				current=current->right;
		}
		if (back->spt->grade>x->grade)
			back->left=newnode;
		else
			back->right=newnode;
	}
}
void Btree::inorder(tree*tmp)  //中序遍历已建立的二叉排序树
{
	if(tmp!=NULL)
	{
		inorder(tmp->left);
		cout<<setw(4)<<list<<setw(6)<<tmp->spt->num<<setw(8)<<tmp->spt->grade<<endl;
		list++;
		inorder(tmp->right);
	}
}

void main()
{
	Btree A;
	sport a[12]={{"001",13.6},{"002",14.8},{"010",12.0},
			{"011",12.7},{"023",15.6},{"025",13.4},
			{"031",14.9},{"036",12.6},{"037",13.4},
			{"102",12.5},{"325",15.3},{"438",12.7}};
    sport * pa[12]={&a[0],&a[1],&a[2],&a[3],&a[4],&a[5],
				&a[6],&a[7],&a[8],&a[9],&a[10],&a[11]};
	cout<<"建立排序二叉树节点的顺序:"<<endl;
	for (int i=0;i<12;i++)
	{
		cout<<pa[i]->num<<"  "<<pa[i]->grade<<endl;
		A.creat_btree(pa[i]);
	}
	cout<<endl<<"中序遍历此二叉树输出排序后结果:"<<endl;
	cout<<endl;
	A.display();
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -