我相信我的插入功能是正确的,但看起来新节点没有插入树中。我无法弄清楚错误在哪里。感谢您的帮助,谢谢。
有节点和树的声明:
class Node{
int key;
Node *right, *left;
}
class Tree{
public:
int init();
Node *root;
Node *insert(int key, Node *p);
};
有功能:
int Tree::init(){
this->root = NULL; return 1;
}
Node *Tree::insert(int key, Node *p){
if(p == NULL){
Node *novo = new Node();
novo->key = key;
novo->left = NULL;
novo->right = NULL;
p = novo;
}
else if(key < p->key){ p->left = insert(key, p->left); }
else if(key > p->key){ p->right = insert(key, p->right); }
else{ cout << "Error: key already exist" << endl; }
return p;
}
当我在main中调用该函数时,看起来它没有链接新节点
int main() {
Tree dictionary;
cout << "enter the key"; cin >> key;
dictionary.insert(key, dictionary.root);
cout << dictionary.root->key;
}