无法在二叉树中插入新节点
Can't insert a new node in the 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->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 main() {
Tree dictionary;
cout << "enter the key"; cin >> key;
dictionary.insert(key, dictionary.root);
cout << dictionary.root->key;
}
在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
分配更新根指针或最后一个节点的左/右指针),您需要将签名更改为:
Node *insert(int key, Node *& p); // p is passed by reference
这将通过引用传递指针p
。修改p将具有修改用于调用函数的指针的效果,并且将承受插入的持久效果。
相关文章:
- 节点 *temp; 和节点 *tmp = 新节点之间的差异
- 为什么我的节点在我设置后被设置为 nullptr = 新节点?
- 指向二叉树中新节点的指针
- 如果我们不创建一个新节点并使用指针插入数据并建立链接(在链表中)怎么办?
- C++ 如何使用动态计算的新节点实现 A*?
- 如何在使用 ItemType 的模板类时将新节点插入二叉树 c++.(我是 c++ 的新手)
- 在不创建新节点的情况下实现带有映射的trie
- 添加新节点后,链接列表的负责人总是无效
- 推送功能(将新节点添加到列表顶部)C
- 二叉树不接受新节点
- 使用括号会在声明新节点时会产生错误
- C++链表将新节点添加到列表的开头
- C++为什么创建一个新节点来删除堆栈上的节点是错误的
- 如何在双链接列表中创建新节点?(C++)
- 了解如何在链接列表末端添加新节点
- 创建新节点的困难
- C++ 在链表中间插入新节点时出现问题
- 将新节点添加到列表中并动态命名
- C++:尝试将新节点添加到链表会产生"线程 1:EXC_BAD_ACCESS(代码 = 1,地址 = 0x0)"错误
- 在头部添加新节点