0
我很难让插入功能正常工作。 cout声明与我的作业不匹配。如果我尝试插入5,我得到inserted: 5 right child of: 3
,但应该是inserted: 5 right child of: 22
有人可以帮我吗?BST插入值
Node* insert(Node *root, int value){
Node *tmp = root;
while(tmp != NULL){
if (tmp->key == value){
return tmp;
}
else if (value > tmp->key){
Node *tm = new Node(NULL, NULL, NULL);
tm->key = value;
tm->left = tmp->right;
tm->right = tmp->left;
tmp->right = tm;
cout << "inserted: " << tm->key << " right child of: " << tmp->key <<endl;
tmp = tmp->right;
}
else if (value < tmp->key){
Node *tm = new Node(NULL, NULL, NULL);
tm->key = value;
tm->left = NULL;
tm->right = NULL;
tmp->left = tm;
cout << "inserted: " << tm->key << " left child of: " << tmp->key <<endl;
tmp = tmp->left;
}
}
return tmp;
}
您的代码插入新值作为根节点的子节点。你应该首先找到新价值的地方。 –
您应该递归,直到找到正确的位置。 – molbdnilo