首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

关于二叉搜索树的c代码实现有关问题

2013-06-25 
关于二叉搜索树的c代码实现问题!代码是二叉树定义接口, 二叉树的实现,还是应用二叉树接口解决实际问题,由

关于二叉搜索树的c代码实现问题!
代码是二叉树定义接口, 二叉树的实现,还是应用二叉树接口解决实际问题,
由于代码比较长,我想各位大神也不愿意看,所以更具出错信息,将有可能出错的代码帖在下面,请大神们指教啊!


// 部分 tree.c
// 一段添加 item 的代码段
int AddItem (const Item * pitem, Tree * ptree)
{
Node * new_node;

if (TreeIsFull (ptree))
{
printf ("Tree is full.\n");
return FALSE;
}
if (SeekItem (pitem, ptree).child != NULL)
{
puts ("Attempted to add duplicate item.");
return FALSE;
}
new_node = MakeNode (pitem);

if (new_node == NULL)
{
puts ("Could't create node.");
return FALSE;
}

// 成功创建一个新节点
ptree->size++;
if (ptree->root == NULL)
ptree->root = new_node;
else
AddNode (new_node, ptree->root);
return TRUE;

}
static int ToLeft (const Item * i1, const Item * i2)  // 搜索的项目在左子树,返回true;
{
int comp1;

if ((comp1 = strcmp(i1->word, i2->word)) < 0)
return TRUE;
else 
return FALSE;
}

static int ToRight (const Item * i1, const Item * i2)
{
int comp1;

if ((comp1 = strcmp(i1->word, i2->word)) > 0)
return TRUE;
else 
return FALSE;
}

static void AddNode (Node * new_node, Node * root)
{
if (ToLeft (&(new_node->item), &(root->item)))
{
if (root->left == NULL)
root->left = new_node;
else 
AddNode (new_node, root->left);
}
if (ToRight (&(new_node->item), &(root->item)))
{
if (root->right == NULL)
root->right = new_node;
else AddNode (new_node, root->right);
}
else 
{
puts ("location error in AddNode()."); 
exit (1);
}
}

//读取文件,应用这个二叉搜索树 来 存储文件中出现的单词 以及单词出现的次数;

while (fscanf (fp, "%s", words) == 1)
{
strcpy (single_word.word, words);

//Pair SeekItem (const Item * pitem, const Tree * ptree);// 匹配项目

if ((target = SeekItem (&single_word, &list).child )!= NULL)
{
target->item.time++;
}
else
{
single_word.time = 1;
AddItem (&single_word, &list); // 这个有问题啊! 还必须按照字母表顺序;
}

}
// 如果文件中的单词是这样的会就会没有问题---- a b c d ----按字母表顺序;
// 但一改变顺序就会打印出 : location error in AddNode().-------也就是addnode()函数else情况下出现的语句
// 这是什么原因照成的啊?  那里逻辑出现了问题啊? 



------解决方案--------------------


    if (ToRight (&(new_node->item), &(root->item))) 
试改为
    else if (ToRight (&(new_node->item), &(root->item))) 

热点排行
Bad Request.