尝试使二叉搜索树适应两个参数,崩溃(C++)

Trying to Adapt Binary Search Tree for Two Parameters, Getting Crash (C++)

本文关键字:两个 参数 C++ 崩溃 搜索树      更新时间:2023-10-16

对于赋值,我需要实现二叉搜索树的几个函数。我得到了看似逻辑的代码,但是,每当我尝试实现插入节点功能时,我都会遇到程序崩溃。这是我的插入函数代码:

    void insert (K k, V v)
    {
        TreeNode<K,V> * treeNode = NULL;
        TreeNode<K,V> *temp=NULL;
        TreeNode<K,V> *prev=NULL;
        temp = root;
    while(temp)  //This is the loop that causes a crash, even if I remove the loop.
    {
        prev = temp;
        if (temp->key < treeNode->key)
            temp = temp->right;
        else
            temp = temp->left;
    }
    if (prev==NULL)
        root = treeNode;
    else
    {
        if (prev->key<treeNode->key)
            prev->right = treeNode;  
        else
            prev->left = treeNode;
    }


    }

我还将包括 TreeNode 类:

template <class K, class V> class TreeNode
{
public:
TreeNode(K k, V v): key(k), value(v), left(0), right(0) {}
K       key;
V       value;
TreeNode<K,V>   *left;
TreeNode<K,V>   *right;
template <class X, class Y> friend std::ostream & operator 
<< (std::ostream &s,const TreeNode<X,Y> &t);    
};

当我尝试执行命令t.insert("bob","bobdata")时; bam,立即崩溃。我已经注释掉了各种参数,并发现指示的部分是问题所在,尽管除此之外我卡住了。即使我删除循环并且只执行一次,它也会发生,所以我不会陷入无穷大。我觉得这可能与我传递字符串的事实有关,但我不确定,如果这是问题所在,我没有足够的知识来解决它。 有没有人可以告诉我我在这里做错了什么?非常感谢!

您是否在

循环之前将treeNode分配给任何地方? 看起来treeNodeNULL所以当你在条件中取消引用它时,它会抛出一个异常:

if (temp->key < treeNode->key)  // This throws an exception if treeNode is not set
                ^^^^^^^^^^^^^
下面的示例实现,

你需要支持 c++11 才能编译(因为nullptr,为了兼容 C++ 而用 NULL 替换)。

#include <iostream>
using namespace std;
template <template<class K, class V> class TreeNode, class K, class V>
std::ostream & operator<< (std::ostream &s,const TreeNode<K,V> &t);
template <class K, class V>
class TreeNode
{
public:
  typedef TreeNode<K,V> SelfType;
  TreeNode(K k, V v): key(k), value(v), left(nullptr), right(nullptr) {}
  K       key;
  V       value;
  SelfType   *left;
  SelfType   *right;
  friend std::ostream & operator<< <>(std::ostream &s,const SelfType &t);    
};
template <class K, class V>
struct Tree {
  typedef TreeNode<K,V> NodeType;
  NodeType *root;
  Tree() : root(nullptr){}
  void insert (K k, V v)
  {
    NodeType * treeNode = new NodeType(k,v);
    NodeType *temp = nullptr;
    NodeType *prev = nullptr;
    temp = root;
    while(temp) {
      prev = temp;
      if (temp->key < treeNode->key)
        temp = temp->right;
      else
        temp = temp->left;
    }
    if (prev==nullptr)
      root = treeNode;
    else {
      if (prev->key<treeNode->key)
        prev->right = treeNode;  
      else
        prev->left = treeNode;
    }
  }
};
int main(){
  Tree<int,int> t;
  t.insert(1,2);
}

我只对KV模板参数使用 int 进行了测试,因为它避免了与复制构造函数相关的任何问题。您可能希望让所有方法都引用KV而不是纯值。

遇到了一个问题:

  • NULL初始化treeNode变量insert

代码中可能存在的问题:

  • Tree类中未初始化的root