I need to put inside an array, the values of a binary tree, but the thing is, I should only put inside the array the values that are at a certain depth. And it should output the number of elements inserted at the array.
I have made this:
int nivel2_(ABin a, int n, int v[], int level, int *i){
int t;
if(!a) return 0;
if(n == level){
v[(*i)++] = a->value;
return 1;
}else{
t = nivel2_(a->left, n, v, level+1, i) + nivel2_(a->right, n, v, level+1, i);
}
return t;
}
int nivel2(ABin a, int n, int v[]){
int k = 0;
int *i;
i = &k;
return nivel2_(a, n, v, 1, i);
}
As I will keep changing the index recursively and only when we reach the depth we want, I thought of using a pointer, this way, when one part of the recursive folding happens it will change the value to all the other folding processes. Makes sense?
Structures:
typedef struct slist
{
int value;
struct slist* next;
} *SList;
typedef struct arvbin* ABin;
typedef struct arvbin
{
int value;
ABin right;
ABin left;
} arvb;
DOES IT WORK?
Only when I want the elements of the first level of depth!
Calling like this:
nivel2(tree2, 1, v);
Complete code
#include <stdio.h>
#include <stdlib.h>
typedef struct slist
{
int value;
struct slist* next;
} *SList;
typedef struct arvbin* ABin;
typedef struct arvbin
{
int value;
ABin right;
ABin left;
} arvb;
int nivel2_(ABin a, int n, int v[], int level, int *i){
int t;
if(!a) return 0;
if(n == level){
v[(*i)++] = a->value;
return 1;
}else{
t = nivel2_(a->left, n, v, level+1, i) + nivel2_(a->right, n, v, level+1, i);
}
return t;
}
int nivel2(ABin a, int n, int v[]){
int k = 0;
int *i;
i = &k;
return nivel2_(a, n, v, 1, i);
}
void insertTree(ABin *tree, int val){
if((*tree)==NULL){
*tree = (ABin) malloc(sizeof(arvb));
(*tree)->value = val;
(*tree)->left = NULL;
(*tree)->right = NULL;
return;
}
else if(val > (*tree)->value)
{
insertTree(&((*tree)->right), val);
}
else if(val <= (*tree)->value)
{
insertTree(&((*tree)->left), val);
}
return;
}
int main(){
int v[10] = {0};
ABin tree2 = NULL;
insertTree(&tree2, 22);
insertTree(&tree2, 1);
insertTree(&tree2, 3);
nivel2(tree2, 1, v);
int i;
for(i=0; i<5; i++){
printf("%d\n", v[i]);
}
return 0;
}