Quantcast
Channel: convert array to binary tree with recursive strategy - Stack Overflow
Viewing all articles
Browse latest Browse all 3

Answer by ggorlen for convert array to binary tree with recursive strategy

$
0
0

First of all, int a[] = {10,4,7,2,3,-1,8,9,-1,2,4,5}; shouldn't produce the tree you expect, with 5 as the left child of 8. Since 8 is at index 6, its left child would be at index 6 * 2 + 1 == 13. So your input should probably be int a[] = {10,4,7,2,3,-1,8,9,-1,2,4,-1,-1,5};, with two extra -1s towards the end of the array to push 5 to the correct index.

Your implementation can't work because in the pattern:

{    Bit_node new_node = malloc(...)}return new_node;

new_node is being accessed when not in scope. If you encounter a -1, you want to return NULL just like you're doing if you go out of bounds on the array. Returning NULL says "there is no child here", which is exactly what you want to communicate to a parent frame so that it sets the missing child to NULL.

The fix should be pretty straightforward:

Bit_node bit_arr2tree(int a[], int size, int i) {    if (i>= size || a[i] < 0) {    //           ^^^^^^^^^^^        return NULL;    }    Bit_node new_node = bit_new(a[i]);    new_node->sx = bit_arr2tree(a, size, i * 2 + 1);    new_node->dx = bit_arr2tree(a, size, i * 2 + 2);    return new_node;} 

As an aside, I'd caution against typedeffing away pointers. This makes the code less readable and hides information.

Here's a runnable proof of concept:

#include <stdio.h>#include <stdlib.h>struct Node {    int data;    struct Node *left;    struct Node *right;};struct Node *arr2tree(int arr_len, int *arr, int i) {    if (i >= arr_len || arr[i] < 0) {        return NULL;    }    struct Node *node = malloc(sizeof(*node));    node->data = arr[i];    node->left = arr2tree(arr_len, arr, i * 2 + 1);    node->right = arr2tree(arr_len, arr, i * 2 + 2);    return node;}void print_tree(struct Node *root, int depth) {    if (root) {        print_tree(root->right, depth + 4);        for (int i = 0; i < depth; i++) {            printf(" ");        }        printf("%d\n", root->data);        print_tree(root->left, depth + 4);    }}void free_tree(struct Node *root) {    if (root) {        free_tree(root->left);        free_tree(root->right);        free(root);    }}int main() {    int a[] = {10,4,7,2,3,-1,8,9,-1,2,4,-1,-1,5};    struct Node *root = arr2tree(sizeof(a) / sizeof(a[0]), a, 0);    print_tree(root, 0);    free_tree(root);    return 0;}

Output:

        8            5    710            4        3            2    4        2            9

Viewing all articles
Browse latest Browse all 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>