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

convert array to binary tree with recursive strategy

$
0
0

I need to create a binary tree starting from vector containing some zeros where a zero represents a node that doesn't exists. for example if I got:

int a[] = {10,4,7,2,3,-1,8,9,-1,2,4,5};

I would like my output like this:

         10        /   \       4     7      / \     \     2   3     8    /   / \   /   9   2   4 5  

my struct:

  typedef struct node {   int n;   struct node * dx;   struct node * sx;  } *Bit_node;          

method to build one node:

  Bit_node bit_new(int n) {    Bit_node new_node = malloc(sizeof(struct node));    new_node -> n = n;    return new_node;  }   

method to build the whole tree:

  Bit_node bit_arr2tree(int a[], int size, int i) {  if (i>= size) {      return NULL;  }  if(a[i] != -1) {   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;} 

But with my implementation my tree is built not considering the "holes". Is there a way to considering them , keeping the recursive strategy?


Viewing all articles
Browse latest Browse all 3

Trending Articles



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