C ++二叉树插入/高度

时间:2017-03-20 04:35:43

标签: 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 );
    }
}

1 个答案:

答案 0 :(得分:1)

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;
}

由于你无法改变类声明(并且它中没有析构函数),我认为你还没有学到这一点,但是你需要注意内存泄漏。