c - Level traversing to print a BST using array of pointers. -
i'm trying traverse level level through tree print it. instead of creating copy of tree, need use dynamic array of pointers tree. it's been 4 hours i'm beginner , couldn't put finger on reason behind segmentation fault. apologise if bug kind of easy spot or if not worth posting:
typedef struct bst{ int value; struct bst* right; struct bst* left; }bstn; //binary search tree node //prototype: int height(bstn* b); void insert(bstn** root, int value); void print(bstn* b); void print(bstn* b){ bstn** level_pointers = (bstn**)malloc( sizeof(bstn*)); level_pointers[0] = b; //copy of pointer root int level_pointers_len = 1; //initial length of array of pointers int new_level_index; int new_level_len; bstn** new_level = (bstn**) malloc(2*level_pointers_len* sizeof(bstn*)); //each new level max twice previous while(1){ new_level_index = 0; (int = 0; < level_pointers_len; i++){ printf("%i \t", level_pointers[i]->value); if (level_pointers[i]->left != null){ new_level[new_level_index] = level_pointers[i]->left; new_level_index ++; } if (level_pointers[i]->right != null){ new_level[new_level_index] = level_pointers[i]->right; new_level_index ++; } printf("\n"); } if (new_level_index == 0) return; new_level_len = new_level_index + 1; level_pointers = (bstn**)realloc(new_level, new_level_len*sizeof(bstn*)); new_level = (bstn**) malloc(2*level_pointers_len* sizeof(bstn*)); level_pointers_len = new_level_len; } }
Comments
Post a Comment