简体   繁体   中英

Sorted Array to BST implementation in C++

I have the following code that takes in a sorted array of integers and converts it into a balanced binary tree :

class node
{
    friend class bst;
public:
    node():data(0), left(NULL), right(NULL){}
    node(int val): data(val), left(NULL), right(NULL){}
private:
    int data;
    node* left;
    node* right;
};

class bst{

public:
    bst():root(NULL){}
    bst(node* root):root(root){}

    node* sorted_array_to_bst(int arr[], int start, int end)
    {
        if(start > end) return NULL;
        int mid = (start + end)/2;
        root = new node(arr[mid]);
        root->left = sorted_array_to_bst(arr, start, mid-1);
        root->right = sorted_array_to_bst(arr, mid+1, end);
        return root;
    }
    void levelorder(node* root)
    {
        if(root == NULL) return;
        std::queue<node*> Q;
        Q.push(root);
        while(!Q.empty())
        {
            node* current = Q.front();
            std::cout<<current->data<<" ";
            if(current->left) Q.push(current->left);
            if(current->right) Q.push(current->right);
            Q.pop();
        }
    }
private:
    node* root;
};

int main() 
{
    int arr[10] = {2,6,7,9,13,15,18,21, 23, 29};
    bst* b;
    node* r = b->sorted_array_to_bst(arr, 0, 9);
    b->levelorder(r);

    return 0;
}

The issue is, when I run the program, 29 gets printed infinitely. I think there is something not right with my main function. Any help would be appreciated.

You did not initialized your bst instance b . You just created it without initialization, so when you call:

node* r = b->sorted_array_to_bst(arr, 0, 9);

your code will crash. You should something like this:

bst* b = new b( /* pass a node */ );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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