dimanche 24 septembre 2017

Handling pointers to create binary tree

I am trying to solve a problem when you are given an array in increasing order and you need to create a binary search tree with minimal height. The problem I am experiencing is the handling pointers. There are a few problems(I suspect) with this code:

1) it returns garbage.It might be algo problem or wrong way of handling pointers.

2) I assume I have to have a destructor for a struct, but I am not sure what will happen if I delete both left and right, and one of them is null. Looks bad.

3) When I get the answer and let's say do some kind of traversal here to prove that it works, I need to delete the entire tree because the way I create is using operator new. I never do it.

4) I believe that there is a solution using smart pointers, but right now my focus is solving interview questions, and the very next thing after that is to study those pointers.

Thanks everyone!

#include <iostream>

using namespace std;

struct BinaryNode
{
    BinaryNode* left;
    BinaryNode* right;
    int val;
    BinaryNode(int val)
    {
        val = val;
        left = NULL;
        right = NULL;
    }
};

BinaryNode* createBinaryTree(int array[], int start, int end)
{
    BinaryNode* root;
    int size = end - start + 1;
    if (size == 0)
        return NULL;
    if (size == 1)
    {
        root = new BinaryNode(array[start]);
    }
    else if (size == 2)
    {
        int index = (start + end) / 2;
        root = new BinaryNode(array[index]);
        root->right = new BinaryNode(index + 1);
    }
    else if (size == 3)
    {
        int index = (start + end) / 2;
        root = new BinaryNode(array[index]);
        root->right = new BinaryNode(index + 1);
        root->left = new BinaryNode(index - 1);
    }
    else
    {
        int index = (start + end) / 2;
        root = new BinaryNode(array[index]);
        root->left = createBinaryTree(array, start, index - 1);
        root->right = createBinaryTree(array, index + 1, end);
    }
    return root;
}


int main()
{
    BinaryNode* root;
    int array[6] = { 1, 2, 3 , 4, 5 };
    root = createBinaryTree(array, 0, 5);
    cout << root->val << endl;
}

Aucun commentaire:

Enregistrer un commentaire