c++ - 无法在二叉树中插入新节点

标签 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->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;
}

最佳答案

在 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 将具有修改您用来调用该函数的指针的效果,并将承受插入的持久影响。

关于c++ - 无法在二叉树中插入新节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36535594/

相关文章:

c++ - LuaBind:如何将类的特定实例绑定(bind)到 Lua?

检查二叉树的路径是否等于给定的总和

f# - 如何使这个 F# 函数不会导致堆栈溢出

创建一个包含某一级别节点值的数组

java - 如何在Java中打印二叉 TreeMap ?

c++ - 如何在 C++ 中使用 .so 库与 Clion 和 Cmake?

c++ - 如何在 Eclipse 中使用 nix

c++ - 如何在没有库的情况下在 C++ 中初始化套接字

java - 高尔夫纸牌的游戏状态树

Xcode 4 首选项 Pane 缺少 "Source Trees"选项卡?