【问题标题】:Tree not being created未创建树
【发布时间】:2019-11-01 10:03:06
【问题描述】:

当我调用函数 createBst() 时,程序在函数中终止。

我在函数后面放了一条打印语句,但它没有被调用。下一个打印语句“终止”没有被调用

int main(){
    bst b;
    b.createBst();
    std::cout<<"terminated"<<std::endl;
    return 0;
}
class node{
public:
    int val;
    node* left;
    node* right;
};

class bst{

public:
    node* head;
    void createBst();
    node* newNode(int val);

};

node* bst::newNode(int v){
    node n1;
    node* n=&n1;
    n->val=v;
    n->left=nullptr;
    n->right=nullptr;
    return n;
}

void bst::createBst(){
    head=bst::newNode(10);
    head->left=bst::newNode(11);
    (head->left)->left=bst::newNode(7);
    head->right=bst::newNode(9);
    (head->right)->left=bst::newNode(15);
    (head->right)->right=bst::newNode(8);
}

输出应该是“终止的”。

【问题讨论】:

  • 类应在main中使用前定义。

标签: c++ class oop tree definition


【解决方案1】:

对于初学者来说,应该在 main 中使用之前定义类。

这个函数

node* bst::newNode(int v){
    node n1;
    node* n=&n1;
    n->val=v;
    n->left=nullptr;
    n->right=nullptr;
    return n;
}

调用未定义的行为,因为它返回指针 ro 一个局部变量 n1,该变量在退出函数后将不再存在。

函数可以这样定义

node* bst::newNode(int v)
{
    return new node { v, nullptr, nullptr };
}

其实函数可以是私有的静态成员函数

class bst{
public:
    node* head;
    void createBst();

private:
    static node* newNode(int val);
};

并且类节点应该是类bst的嵌套私有(或受保护)类。

此外,您还需要一个用于将 head 初始化为 nullptr 的类 bst 的默认构造函数,或者您必须在类定义中将 head 显式初始化为 nullptr,例如

class bst{

public:
    node* head = nullptr;
    void createBst();

private:
    static node* newNode(int val);

};

要将数据插入树中,您应该编写一个函数,例如这样

void insert( int value )
{
    node **current = &head;

    while ( *current != nullptr )
    {
        if ( value < ( *current )->val )
        {
            current = &( *current )->left;
        }
        else
        {
            current = &( *current )->right;
        }
    }

    *current = newNode( value );
}

【讨论】:

  • 删除之前的评论
猜你喜欢
  • 1970-01-01
  • 2015-06-09
  • 2016-01-15
  • 1970-01-01
  • 2012-01-14
  • 2013-01-30
  • 1970-01-01
  • 2017-07-01
  • 2011-12-18
相关资源
最近更新 更多