尝试适应两个参数的二进制搜索树,获取崩溃(C ++) [英] Trying to Adapt Binary Search Tree for Two Parameters, Getting Crash (C++)

查看:151
本文介绍了尝试适应两个参数的二进制搜索树,获取崩溃(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For an assignment, I need to implement several functions of a binary search tree. I've gotten what seems like logical code, however, whenever I try and implement the insert node function, I get a program crash. Here is my code for the insert function:

    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类:

I'll also include the TreeNode class:

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,立即崩溃。我注释掉了各种参数,发现指出的部分是问题,虽然超出了我被卡住了。它发生即使我删除循环,只执行一次,所以我没有陷入无限。我觉得它可能与事实有关的事实,我传递字符串,但我不知道肯定,并不知道足够解决它,如果这是问题。有没有人可以告诉我我在这里做错了?非常感谢!

And when I try and execute the command t.insert("bob", "bobdata"); bam, immediate crash. I've commented out various parameters and discovered that the indicated section is the issue, although beyond that I'm stuck. It happens even if I remove the loop and only execute once, so I'm not getting stuck in infinity. I feel like it may have something to do with the fact that I'm passing strings, but I don't know for sure, and am not knowledgeable enough to fix it if this is the problem. Is there anyone that can tell me what I'm doing wrong here? Thanks so much!

推荐答案

你在循环之前分配 treeNode ?它看起来像 treeNode NULL 所以当你解除它在条件中引用一个异常:

Do you assign treeNode anywhere before the loop? It looks like treeNode is NULL so when you dereference it in the conditional it throws an exception:

if (temp->key < treeNode->key)  // This throws an exception if treeNode is not set
                ^^^^^^^^^^^^^

这篇关于尝试适应两个参数的二进制搜索树,获取崩溃(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆