BST 不添加元素
BST not adding elements
所以我编写了这段代码来向下图所示的二进制 Tree.As 添加元素。
typedef struct node{
int key;
node *right;
node *left;
}*nodePtr;
nodePtr root = NULL // As global variable.
void addElement(int key, nodePtr tempRoot){
if(tempRoot!=NULL){
if(tempRoot->key > key){
if(tempRoot->left!=NULL)
addElement(key, tempRoot->left);
else
tempRoot->left = createLeaf(key);
}
else if(tempRoot->key < key){
if(tempRoot->right!=NULL)
addElement(key, tempRoot->right);
else
tempRoot->right = createLeaf(key);
}
}else if(tempRoot==NULL)
tempRoot = createLeaf(key);
}
int main(){
int arr[] = {50,45,23,10,8,1,2,54,6,7,76,78,90,100,52,87,67,69,80,90};
for(int i=0; i<20; i++){
addElement(arr[i], root);
}
return 0;
}
问题是当我尝试打印树时,此代码不会向树添加任何内容。但是,如果我用此代码替换代码的最后一部分;
else if(root==NULL)
root = createLeaf(key);
为什么会这样?
您按值接收 tempRoot,因此在函数内部更改它不会反映在外部。当你直接访问全局root
时,你确实可以在函数内部更改它的值。
void addElement(int key, nodePtr tempRoot){
您可以在此处使用参考资料。
void addElement(int key, nodePtr &tempRoot)
相关文章:
- 使用std::transform将一个范围的元素添加到另一个范围中
- 如何将元素添加到数组的线程安全函数?
- 如何将元素添加到向量的字符串位置
- 将数组的元素添加到链表中
- 如何在C++中将元素添加到非固定大小的数组中?
- 如何使用模板根据类型将元素添加到各种容器中
- 将在堆栈上声明的元素添加到静态数组
- 有什么方法可以将元素添加到列表中,如图所示?
- 继承层次结构并将元素添加到向量
- gStreamer 将元素添加到通过 gst_parse_launch 创建的管道中
- 将新元素添加到列表中,并返回对该元素的引用?
- 将元素添加到 std::list 在多线程中,无需 C++ 互斥锁
- C++如何通过超出大小将元素添加到指针数组中
- 将集合的随机元素添加到列表中,然后将其从原始集合中移除
- 将字符串集合中的元素添加到字符串集合的向量中
- 为什么 memcpy() 是一种将元素添加到 'std::map' 的方法?
- 如何有条件地将元素添加到 std::array - C++11
- 如何在 c++ 中将元素添加到数组的最后一个
- 如何使用<<运算符将元素添加到向量?
- 将元素添加到结构向量的全球向量中