简体   繁体   English

将值插入C中的二叉搜索树?

[英]insert values into a binary search tree in C?

I have a .h file that contains my struct and I must NOT edit this file: 我有一个包含我的struct的.h文件,我不能编辑这个文件:

struct KnightTree 
{
    int key;
    int level; 
    int balance;            //will be used in AVL only, and be ignored in other cases.
    KnightTree* pLeftChild;
    KnightTree* pRightChild;
};

And a .cpp file that I write my code here, I've written a code to insert 2 values (key and level) into the BST: 我在这里编写代码的.cpp文件,我编写了一个代码,将2个值(键和级别)插入到BST中:

void BSTinsert(KnightTree* tree, int k, int lvl)
{
    KnightTree* newnode;
    if (tree == NULL)
    {
        newnode->key=k;
        newnode->level=lvl;
        newnode->pLeftChild=NULL;
        newnode->pRightChild=NULL;
        tree = newnode;
    }
    else
    {
        if (tree->key > k)
            BSTinsert(tree->pLeftChild,k,lvl);
        else if (tree->key <= k)
            BSTinsert(tree->pRightChild,k,lvl);
    }
}

But when I run it, the console "thinks" itself for about 3 seconds and error pop-up said "exe has stop working" so I have to close the program . 但是当我运行它时,控制台“认为”自己大约3秒钟并且错误弹出窗口说“exe已经停止工作”所以我必须关闭程序 I think's simple but I'm kinda confused now... I'm using Visual C++ 6.0 (I have to use this old version...) 我觉得很简单,但我现在有点困惑......我正在使用Visual C ++ 6.0(我必须使用这个旧版本......)

Thank you guys! 感谢大伙们!

You have at least 2 major problems: 您至少有两个主要问题:

  1. You do not allocate memory for your newnode , so by addressing it you just create memory corruption. 您没有为newnode分配内存,因此通过解决它只会造成内存损坏。
  2. You do not attach your newly created node to the tree, assigning tree = newnode doesn't create the necessary link to the tree. 您没有将新创建的节点附加到树,指定tree = newnode不会创建到树的必要链接。

Proceed from fixing these 2 issues. 从解决这两个问题开始。

And one more thing: have you tried to actually debug it before posting the question here? 还有一件事:你有没有试过在发布问题之前实际调试它?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM