0

有人可以告诉我我的程序有什么问题吗?这基本上是一个在二叉搜索树中插入新节点的程序。

问题是我的插入功能正常工作并且节点正在被插入,我正在通过行在主程序中进行验证

     cout<<a.left->right->right->data;

其输出正确,即 5

但是当我尝试打印二叉树的级别顺序遍历时,一些垃圾值被传递来代替新节点并且程序正在崩溃

有人可以看看并向我解释我做错了什么以及如何在主程序中显示正确的值。

#include<iostream>
#include<string>
#include<conio.h>
#include<array>
#include<stack>
#include<sstream>
#include<algorithm>
#include<vector>
#include<ctype.h>//isdigit
#include<deque>
#include<queue>
#include<map>
using namespace::std;
struct BST
{
    int data;
    BST *left;
    BST *right;
    BST(int d,struct BST* l,BST *r):data(d) , left(l) ,right(r)
    {
    }
};

void levelOrder(struct BST *root)
{
    struct BST *temp=NULL;
    int count =0;
    deque<struct BST*> dq;
    if(!root)
    {
        return;
    }
    dq.push_back(root);
    count=dq.size();
    while(!dq.empty())
    {
        temp=dq.front();
        cout<<temp->data<<" ";
        if(temp->left)
        {
            dq.push_back(temp->left);
        }
        if(temp->right)
        {
            dq.push_back(temp->right);
        }
        dq.pop_front();
        if(--count==0)
        {
            cout<<endl;
            count=dq.size();
        }
    }
}
void Insert(struct BST*root,int data)
{
    struct BST temp(data,NULL,NULL);
    if(!root)
    {
        return;
    }
    while(root)
    {
        if((root)->data >data)
        {
            (root)=(root)->left;
            if(!(root)->left)
            {
                (root)->left=&temp;
                break;
            }
        }
        else
        {
            (root)=(root)->right;
            if(!(root)->right)
            {
                (root)->right=&temp;
                break;
            }
        }
    }
}
int main()
{
    deque<struct BST> dq1,dq2;
    BST e(4,NULL,NULL);
    BST f(3,NULL,NULL);
    BST d(1,&f,NULL);
    //BST g(4,NULL,NULL);
    BST b(2,&d,&e);
    BST c(8,NULL,NULL);
    BST a(6,&b,&c);
    levelOrder(&a);
    Insert(&a,5);
    cout<<a.left->right->right->data;
    cout<<endl;
    levelOrder(&a);
    _getch();
    return 0;
}
4

1 回答 1

3

Insert原因是因为您在函数的树中放入了指向局部变量的指针。

当一个函数返回时,它的所有局部变量都不再“活着”,并且访问指向这些局部变量之一的指针是未定义的行为。事实上,这些变量曾经占用的内存可能会被下一个函数调用覆盖,无论你调用什么函数。

如果要添加新节点,则需要使用 eg 在堆上分配它new。但是,由于您对树的设计,这将导致内存泄漏,因为您没有释放任何子节点。事实上,当您在main函数中使用指向局部变量的指针时(没关系,因为这些变量的生命周期main是整个程序的持续时间),您不能只是简单地delete使用指针。

于 2013-03-02T21:27:37.113 回答