jeudi 3 décembre 2020

binary search tree function that returns the median value within the struct

my code is trying to return the median value of a binary search tree. However, when I compile it with the test case, I'm getting a segmentation error.

My code so far:

void inorder(BTnode_t *root){    //helper function
    int i;
    int arr[i++]; 
    inorder(root->left);
    arr[i++] = root->value;
    inorder(root->right);
}

int get_median(BST_t *tree){
    int median = 0;
    int i;
    int arr[i++];
    inorder(tree->root);

    if(i%2 == 0){
        median = (arr[i/2]+arr[(i/2)-1])/2;
    } 
    else {
        median =  arr[i/2];
    }
    return median;
}

Test code that returns segmentation fault:

bool test_q2b()  {
    BST_t *bst = create_BST();
    BST_insert(bst, 0);
    BST_insert(bst, -27);
    BST_insert(bst, -53);
    BST_insert(bst, -13);
    BST_insert(bst, 5);
    BST_insert(bst, 125);
    BST_insert(bst, 93);
    BST_insert(bst, 127);

    if (get_median(bst) == 5)  {
        printf("AC\n");
        return true;
    }
    else  {
        printf("WA\n");
        return false;
    }
}

int main()  {
    test_q2b();

    return 0;
}

Any help is appreciated.

Aucun commentaire:

Enregistrer un commentaire