void avl::bst_to_array(avl_node* n, int i){ if(n == NULL) return; a[i] = n; int left = 2*(i)+1; int right = 2*(i)+2; bst_to_array(n -> get_lchild(), left); bst_to_array(n -> get_rchild(), right); }
void t_avl() { int i; BST_PTR t = bst_create(); int *a = gen_random_arr(SAMPLE_SIZE); for(i=0; i<SAMPLE_SIZE; i++) bst_insert(t, i); printf("Height of root: %d\n", bst_height(t)); printf("Size of tree: %d\n", bst_size(t)); printf("Min elem: %d\n", bst_min(t)); printf("Max elem: %d\n", bst_max(t)); printf("Nearest elem: %d\n", bst_get_nearest(t,500)); printf("Num LEQ: %d\n", bst_num_leq(t,10)); for(i=0; i<SAMPLE_SIZE-1; i++) { bst_remove(t,a[i]); printf ("Delete %d\n", a[i]); } assert(bst_to_array(t)[0]==a[SAMPLE_SIZE-1]); printf("Height of root: %d\n", bst_height(t)); printf("Size of tree: %d\n", bst_size(t)); printf("Min elem: %d\n", bst_min(t)); printf("Max elem: %d\n", bst_max(t)); printf("Nearest elem: %d\n", bst_get_nearest(t,500)); printf("Num LEQ: %d\n", bst_num_leq(t,10)); free(a); bst_free(t); }
int main(){ int i; /* PART 1 */ int a[] = {8, 2, 6, 9, 11, 3, 7}; BST_PTR t = bst_create(); t_avl(); // t_height(); /* PART 2 */ // bst_inorder(t); // // bst_preorder(t); // // bst_postorder(t); bst_free(t); int sorted_a[] = {2, 3, 6, 7, 8, 9, 11}; t = bst_from_sorted_arr(sorted_a, 7); int *b = bst_to_array(t); printf("Height of root: %d\n", bst_height(t)); printf("Size of tree: %d\n", bst_size(t)); printf("ith smallest element: %d\n", bst_get_ith(t,10)); printf("Num LEQ: %d\n", bst_num_leq(t,3)); printf("A: "); for (i=0; i<7; i++) { printf("%d ", sorted_a[i]); } printf("\n"); printf("B: "); for (i=0; i<7; i++) { printf("%d ", b[i]); } printf("\n"); free(b); bst_free(t); }
void avl::print_tree(){ string value; for(int j = 0; j < BST_ARRAY_SIZE; j++){ a[j] = NULL; } bst_to_array(_root, 0); for(int i = 0; i < 31;i++){ if(i == 1 || i == 3 || i==7 || i == 15){ cout<<endl; } if(a[i] == NULL){ cout<<"[ ]"; } else{ cout<<"["<<(a[i] -> get_word())<<", "<<(a[i] -> get_balance())<<"]"; } } cout<<endl; }