C++ 二叉树插入/高度

标签 c++ recursion tree

我似乎无法弄清楚这段代码哪里出错了。这是为了类作业,我必须在高度最低的地方插入二叉树。

我在高度函数中遇到明显的段错误。

class Node {
    public:
        Node();
        Node( int );

    private:
        friend class bT;
        int data;
        Node* left;
        Node* right;
};

class bT {
    public:
        bT();
        virtual void insert( int );
        int height() const;
        unsigned size() const;

    protected:
        Node* root;

    private:
        void insert( Node*&, int );
        int height( Node* ) const;
};

还有我的主文件:

int bT::height() const {
    //Returns -1 when root does not exist
    if ( root == NULL )
        return -1;

    //Calls private recursive method. Uses taller height
    int lheight = height( root->left );
    int rheight = height( root->right );

    if ( lheight > rheight )
        return lheight;
    else
        return rheight;
}


void bT::insert( int x ) {
    //Inserts new node at root if root does not exist
    if ( root == NULL ){
        Node node( x );
        root = &node;
    }

    //Calls private recursive method to insert.
    else {
        int lheight = height( root->left );
        int rheight = height( root->right );

        if ( lheight <= rheight )
            insert( root->left, x );
        else
            insert( root->right, x );
    }
}

int bT::height( Node* r ) const {
    //Base Case: Returns 0 when node does not exist
    if ( r == NULL )
        return 0;

    //Calls private recursive method. Uses taller height
    int lheight = height( r->left );
    int rheight = height( r->right );

    if ( lheight > rheight )
        return 1 + lheight;
    else
        return 1 + rheight;
}

void bT::insert(Node*& r, int x){
    //Base Case: Sets r = new node when node does not exist
    if ( r == NULL ) {
        Node node( x );
        r = &node;
    }

    //Recursive Call: Calls insert function for node with lower height
    else {
        int lheight = height( r->left );
        int rheight = height( r->right );

        if ( lheight <= rheight )
            insert( r->left, x );
        else
            insert( r->right, x );
    }
}

最佳答案

insert 方法中的这段代码会导致悬空指针


if ( root == NULL ){
   Node node( x );
   root = &node;
}
//root point to invalid address now

一个简单的解决方法是更改​​为动态分配。


if ( root == NULL ){
   Node* node = new Node( x );
   root = node;
}

因为你不能改变类的声明(而且里面没有析构函数),我想你还没有学过这个,但是你需要小心内存泄漏。

关于C++ 二叉树插入/高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42895926/

相关文章:

c# - 使用 Linq To XML,获取所有叶子路径的方法?

c++ - 在不知道值类型的情况下从前向迭代器获取反向迭代器

c++ - 如何在 MinGW 中启用实验性 C++11 并发功能?

c++ - QPlainTextEdit dragEnterEvent 不接受文本/uri 列表 mime 类型

javascript - Javascript 函数中的递归结束得太快

java - 在java中解析递归未知的json输入结构

JavaScript:如何在它们的功能之外循环遍历这些项目?

c++ - 我还应该使用#include guard 和#pragma 一次吗?

c++ - 2D线段树,矩形之和

c - 在C中将数学方程插入二叉树