65,211
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <stdlib.h>
using namespace std;
typedef struct stu
{
int id;
char name[32];
}STU;
typedef struct tree
{
STU student;
struct tree *lchild,*rchild;
}Tree;
Tree *creatTree(Tree *&root,const int n)//改
{
//Tree **temp;//改
if (root == NULL)
{
root = (Tree*)malloc(sizeof(Tree)*n);//改
if ( root == NULL )
{
cout << "内存分配不成功!" <<endl;
exit(1);
}
else
{
//temp = root;
for (int i=0;i<n;i++)
{
root[i].student.id = i;
}
for ( int j=0; j<n; j++ )
{
//root[j].lchild = &root[j+1];
//root[j].rchild = &root[j+2];
if((2*j+1)<n)
{
root[j].lchild = &root[2*j+1];
}
else
{
root[j].lchild = NULL;
}
if((2*j+2)<n)
{
root[j].rchild = &root[2*j+2];
}
else
{
root[j].rchild = NULL;
}
}
for( int k=((n+1)/2);k <n;k++)
{
root[k].lchild = root[k].rchild = NULL;
}
}
}
return root;
}
void showTree(Tree * root)
{
/*if(root != NULL)
{
if(root->lchild != NULL)
showTree(root->lchild);
if(root->rchild != NULL)
showTree(root->rchild);
cout << root->student.id <<endl;
}*/
if(root == NULL)
{
//do nothing
}
else
{
cout << root->student.id << endl;
showTree(root->lchild);
showTree(root->rchild);
}
}
void main()
{
Tree *root = NULL;
int n;
cin>>n;
root = creatTree(root,n);
showTree(root);
}