【发布时间】:2015-10-01 04:13:24
【问题描述】:
如果我有一个结构:
struct node{
int key_value;
node * p_left;
node * p_right;
};
还有一个添加功能:
node* add(node * p_tree, int key) {
//--The base case of the recursive function will be placed in here
//--since binary trees are recursive in nature and linked data structures
//--are as a whole in terms of space and memory, the recursive function will
//--suffice for most cases involving binary trees.
//--In this case, if the given parameter is null, we create the tree
//--by allocating the necessary memory space
if (p_tree == NULL) {
node * pnew_tree = new node;
pnew_tree->p_left = NULL;
pnew_tree->p_right = NULL;
pnew_tree->key_value = key;
cout << "Added node: " << pnew_tree->key_value << endl;
return pnew_tree;
}// end of base case
//--Depending of the value of the node, we determine if we will add to the left side or the right side of the subtree
if (key < p_tree->key_value){
// if it is less than the value, we add to the left
p_tree->p_left = add(p_tree->p_left, key);
}
else{
p_tree->p_right = add(p_tree->p_right, key);
}
return p_tree;
} // end of function
还有搜索功能:
node* search(node *p_tree, int key) {
//--First:
if (p_tree != NULL) {
if(key == p_tree->key_value){
cout << "Node found" << endl;
return p_tree;
}
if(key < p_tree->key_value){
return search(p_tree->p_left, key);
}
else{
return search(p_tree->p_right, key);
}
}
else{
return NULL;
}
}//--End of recursive search function
为什么我跑的时候会这样:
add(myBinaryTree,1);
cout << "Testing to see if it is there" << endl;
if (search(myBinaryTree,1) == NULL {
cout << "Node not found" << endl;
}
输出是“找不到节点”而不是“找到节点”? 据我所知,add函数不返回NULL,为什么会这样? 我曾尝试研究类似的问题,但无法充分理解其中的代码以提出我自己的解决方案,我也不精通使用我的 IDE(代码块)进行调试,因此不知道该去哪里。 (我只需要一个合乎逻辑的修复,因为我似乎无法在自己身上找到一个)
【问题讨论】:
-
在此处发布之前,您的第一步是在调试器中运行它。
-
为什么你的
add函数返回一个指针?我希望add或insert函数将一个节点添加到列表中;没有预期的返回值。需要更多代码来阐明树的实现方式。 -
@KevinDTimm 如果不是因为我对调试一无所知,那就太好了,如果我知道怎么做,我会很高兴实施上述解决方案并且不会在这里问,但我目前没有时间,需要想出一个快速的解决方案。
-
@Alex_adl04:将您的程序视为学习调试器的第一步。如果您需要快速解决方案,请使用
std::map;或外部库,因为它们已经过调试,从而节省您宝贵的开发时间,可用于学习调试器。 -
要解决这个问题,您应该发布
myBinaryTree的声明,包括所有分配。如果myBinaryTree的成员没有正确初始化,我不会感到惊讶。 @Alex_adl04:您使用的是 C++,而不是 C,因此我强烈建议您在构造函数中初始化结构的成员。 我强烈建议您学习如何使用调试器!对于此类代码,您可以在不到 20 秒的时间内正常解决此类问题。
标签: c++ binary-tree binary-search-tree binary-search