c++ - 二叉搜索树根正在工作,但它不能有任何 child ?

标签 c++ segmentation-fault binary-tree nodes

因此,我尝试为拼写检查器创建自己的 BST,因为我想要附加功能(查找附近的节点以获取建议)。无论如何,我可以创建根节点,但之后就不起作用了。例如,如果我有以下代码:

BST myTree;
myTree.add("rootElement");
myTree.add("abcChild");

如果我公开 root (node *root) 并检查 myTree.root->left !=NULL || myTree.root->right != NULL,我遇到了段错误。我不明白。这是我的一些代码:

struct node {
  string data;
  node *left;
  node *right;
};


void BST::add(string newData)
{
  //Find a position                                                                                                                         
  if (root == NULL){
    root = new node;
    root->data = newData;
    root->left = NULL;
    root->right = NULL;

  }
  else{ //remember to include string                                                                                                        

    if(root->data.compare(newData) < 0){

      // Add to left                                                                                                                        

      addRecursive(root->left, newData);

    }
    else{
      // Add to right                                                                                                                       
      addRecursive(root->right, newData);
    }
  }
}


void BST::addRecursive(node *currentNode, string newData)
{
  if (currentNode == NULL){

    currentNode = new node;
    currentNode->data = newData;
    currentNode->left = NULL;
    currentNode->right = NULL;

  }
  else{ //remember to include string                                                                                                  

    if(currentNode->data.compare(newData) < 0){

      // Add to left                                                                                                                  

      addRecursive(currentNode->left, newData);

    }
    else{
      // Add to right                                                                                                                 
      addRecursive(currentNode->right, newData);
    }
  }
}

这是怎么回事?

最佳答案

添加中,当您这样做时

root = new node;

root 是一个类变量,因此这不是问题,并且是正确的方法。但是,在 addRecursive 中,当您执行时

currentNode = new node;

currentNode 是一个按值传递给函数的指针,因此您只需使局部变量 currentNode 指向内存中的另一个位置。您需要通过引用传递指针,以便当您修改参数时,它会修改原始变量而不仅仅是局部变量。只需将函数 addRecursive 的签名设置为 void addRecursive(node*& currentNode, const string& newData) 即可。这将使指针通过引用传递给函数。

另请注意,我将 string newData 更改为 const string& newData。这样您就可以避免每次调用该函数时在内存中复制该字符串。当您不需要修改传递给函数的字符串拷贝时,您应该在所有函数中进行更改,以提高效率。

关于c++ - 二叉搜索树根正在工作,但它不能有任何 child ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9026334/

相关文章:

python - 如何将二叉树转换为级别字典

Java:二叉树递归方法

c - 从文件读取数据到结构体中 (C)

c++ - 多线程 mex 代码比单线程慢

c++ - 如何用空格读取 cin 直到换行符?

c++ - boost 或 C++0x 中的任何 RAII 模板

c - C 中的段错误(代码转储)错误

c++ - 代码中的段错误

algorithm - 通过添加或乘以节点找到树可以生成的所有数字

c++ - 以给定方向四舍五入的给定精度打印 double