读书人

写一个二叉树构造程序出了点偏题新手

发布时间: 2013-03-21 10:08:17 作者: rapoo

写一个二叉树构造程序出了点难题,新手求教

typedef struct BSTree
{

int key;
struct BSTree * left;
struct BSTree * right;
}Tree;



void CreateBSTree( Tree * root,int key)
{
if(root == NULL)
{
root = new BSTree();
root->left = NULL;
root->right = NULL;
root->key = key;
cout<<root->key;

}
if(root->key>key )
{
if(root->left == NULL)
{
Tree * node = new Tree();
node->left = NULL;
node->right = NULL;
node->key = key;
root->left = node;
}
else
{
CreateBSTree(root->left,key);
}
}
else
{
if(root->right == NULL)
{
Tree * node = new Tree();
node->left = NULL;
node->right = NULL;
node->key= key; root->right = node;
}



然后主函数
int list[]={5,3,4,9,1,7,11};
for(int i=0;i<7;i++)
{
CreateBSTree(root,list[i]);
}
我发现我每次调用时候,root都是空的,意思是我上次for循环给root添加的内容并没有保存,假如可以保存,那么程序肯定就对了,那怎么处理好呢?
[解决办法]
换成引用试试呢。


void CreateBSTree( Tree *& root,int key)

[解决办法]
纯C的话,没有引用,只好用双重指针的办法:
void  CreateBSTree( Tree ** proot,int key) { 


Tree *root=*proot;
...
}
CreateBSTree(&root,list[i]); //调用

读书人网 >C++

热点推荐