BST 不添加元素

BST not adding elements

本文关键字:元素 添加 BST      更新时间:2023-10-16

所以我编写了这段代码来向下图所示的二进制 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)