C++ Can';t在二叉树中插入新节点
我相信我的插入函数是正确的,但看起来新节点没有插入到树中。我想不出哪里出了错。谢谢你的帮助,谢谢 有节点和树的声明:C++ Can';t在二叉树中插入新节点,c++,tree,binary-tree,C++,Tree,Binary Tree,我相信我的插入函数是正确的,但看起来新节点没有插入到树中。我想不出哪里出了错。谢谢你的帮助,谢谢 有节点和树的声明: class Node{ int key; Node *right, *left; } class Tree{ public: int init(); Node *root; Node *insert(int key, Node *p); }; 有以下功能: int Tree::init(){ this->r
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;
}
int-Tree::init(){
this->root=NULL;返回1;
}
节点*树::插入(int键,节点*p){
if(p==NULL){
Node*novo=新节点();
novo->key=key;
novo->left=NULL;
novo->right=NULL;
p=新发;
}
如果(keykey){p->left=insert(key,p->left);}
如果(key>p->key){p->right=insert(key,p->right);}
否则{cout在insert()函数中,当树为空或已到达最后一个节点时,将创建一个新节点:
if(p == NULL){
Node *novo = new Node();
novo->key = key;
novo->left = NULL;
novo->right = NULL;
p = novo; // ouch !!!!
}
不幸的是,语句p=novo
仅更新函数的局部参数p
。它的值将在函数返回后立即消失。它不会更新调用函数时使用的指针。因此树的根仍然为NULL(或最后一个节点的左/右指针)
要获得预期效果(即,您的p
assignment更新根指针或指向最后一个节点左/右的指针),您需要将签名更改为:
Node *insert(int key, Node *& p); // p is passed by reference
这将通过引用传递指针p
。修改p将产生修改用于调用函数的指针的效果,并将承受插入的持久影响。主题外:为什么int-Tree::init()
而不是构造函数?你的MCVE
无法编译-我用gcc
试过了。你还忘了提到他在main
中传递一个未初始化的变量字典。root
,它永远不会工作。谢谢你,Christophe!!!这是一个简单的练习,但我没有注意到这一点detail@AlBundy是的,第因为OP忘了调用init()。用构造函数代替init()可以避免这种讨厌的bug;-)
Node *insert(int key, Node *& p); // p is passed by reference