void bst_inorder(bst b, void f(char *)){ if (b == NULL){ return; } bst_inorder(b->left, f); f(b->key); bst_inorder(b->right, f); }
void bst_inorder(NODE *r, NODE **arr, int *index) { if (r == NULL) { return; } bst_inorder(r->left, arr, index); arr[*index] = r; (*index)++; bst_inorder(r->right, arr, index); }
int main(void) { bst b = bst_new(); printf("inserting d,b,f,a,c,e,g\n"); b = bst_insert(b, "d"); b = bst_insert(b, "b"); b = bst_insert(b, "f"); b = bst_insert(b, "a"); b = bst_insert(b, "c"); b = bst_insert(b, "e"); b = bst_insert(b, "g"); printf("inorder traversal\n"); bst_inorder(b, print_key); printf("preorder traversal\n"); bst_preorder(b, print_key); printf("searching\n"); dosearch(b, "f"); dosearch(b, "o"); dosearch(b, "x"); dosearch(b, "e"); dosearch(b, "d"); bst_free(b); return EXIT_SUCCESS; }
int main(){ int i; int a[] = {8, 2, 7, 9, 11, 3, 2, 6}; BST_PTR t = bst_create(); for(i=0; i<8; i++) bst_insert(t, a[i]); assert(bst_size(t) == 7); test_insert(t); test_contains(t); bst_inorder(t); bst_preorder(t); bst_postorder(t); bst_ith_smallest(t, 1) bst_size(t); bst_free(t); }
/********************************************************************************* * Binary tree inorder traversal. */ static struct query bst_inorder(void *self, void *target){ struct query results = {1,0}; if (self == 0) return results; CodeIndex *rs = (CodeIndex *) self; signed short int root = *((int *) target); if (root == -1) return results; bst_inorder(rs, &rs->countrycodes[root]._lcp); printf("%s.\n", rs->countrycodes[root]._keyid); bst_inorder(rs, &rs->countrycodes[root]._rcp); return results; }
NODE* reBalance(NODE *r) { // in-order parsing the tree and put them in a sorted array NODE **arr = (NODE **)malloc((r->numOfLeft + r->numOfRight + 1) * sizeof(NODE *)); int index = 0; bst_inorder(r, arr, &index); // put all nodes in sorted array NODE *newTree = buildBstFromArr(arr, (r->numOfLeft + r->numOfRight + 1)); // build a new bst from the sorted array free(arr); return newTree; }