int BST_create(struct node **root, int v) { if (*root == NULL) { *root = (struct node *) malloc(sizeof(struct node)); if (*root == NULL) { return 0; } (*root)->v = v; (*root)->left = (*root)->right = NULL; return 1; } if ((*root)->v > v) { return BST_create(&((*root)->left), v); } else { return BST_create(&((*root)->right), v); } }
void BST_test(void) { int i = 10; BST_t *new_bst = BST_create(1000); srand(time(NULL)); for (i = 1; i <= 10; i++) BST_insert(new_bst, rand()%10000); }
void test_binary_tree_search() { // 二叉查找树要求记录的关键字唯一,所以不能有相同的记录 const int length = 11; int array[length] = {65, 32, 49, 10, 8, 72, 27, 42, 18, 58, 91}; int key1 = 72; int key2 = 55; print_array(array, length, " data: "); BSTree tree = NULL; BSTNode* node = NULL; // 创建二叉树 BST_create(&tree, array, length); if (!tree) { printf("Failed to create binary search tree!\n"); return; } // 查找 node = BST_search(tree, key1); printf(" %s %d in binary search tree.\n", (NULL == node) ? "Could not find" : "Yeah! Found", key1); node = BST_search(tree, key2); printf(" %s %d in binary search tree.\n", (NULL == node) ? "Could not find" : "Found", key2); // 插入节点 printf(" Insert %d to binary search tree.\n", key2); BST_insert(&tree, key2); node = BST_search(tree, key2); printf(" %s %d in binary search tree.\n", (NULL == node) ? "Could not find" : "Yeah! Found", key2); // 删除节点 key2 = 27; printf(" Remove %d from binary search tree.\n", key2); BST_remove(&tree, key2); node = BST_search(tree, key2); printf(" %s %d in binary search tree.\n", (NULL == node) ? "Could not find" : "Yeah! Found", key2); // 销毁二叉树 BST_destory(&tree); assert(NULL == tree); }
int main() { int test1[] = {7, 5, 11, 3, 6, 2, 1}; // has 3 paths from root 7 sum as 18 struct node *root = NULL; int i; for (i = 0; i < 7; i++) { assert(BST_create(&root, test1[i]) == 1); } BST_display(root); printf("\n"); int level = 0; level = findPathWithSum(root, 18); printf("\n level = %d\n", level); assert(level == 2); level = findPathWithSum(root, 12); printf("\n level = %d\n", level); assert(level == 0); return 0; }