diff --git a/tests/test.c b/tests/test.c index 8678185109c21940312f58df858097241c17e49c..cea1e8e48a88d5c7f0e3202ba51e9ca8a82381cd 100644 --- a/tests/test.c +++ b/tests/test.c @@ -134,6 +134,26 @@ static MunitResult test_tree_find_max() return MUNIT_OK; } +static MunitResult test_tree_search() +{ + node_t* nd = bst_create(); + munit_assert_true(bst_is_empty(nd)); + nd = bst_insert(nd,12); + nd = bst_insert(nd,22); + nd = bst_insert(nd,32); + nd = bst_insert(nd,42); + nd = bst_insert(nd,2); + nd = bst_insert(nd,3); + nd = bst_insert(nd,4); + nd = bst_insert(nd,5); + nd = bst_insert(nd,10); + nd = bst_insert(nd,50); + munit_assert_ptr_not_null(bst_search(nd,50)); + munit_assert_ptr_null(bst_search(nd,5239487)); + bst_destroy(nd); + return MUNIT_OK; +} + static MunitResult test_tree_is_BST() { node_t* nd = bst_create(); @@ -222,6 +242,14 @@ static MunitTest test_suite_tests[] = { MUNIT_TEST_OPTION_NONE, NULL }, + { + (char*) "/test_tree_search", + test_tree_search, + NULL, + NULL, + MUNIT_TEST_OPTION_NONE, + NULL + }, // { // (char*) "/test_tree_is_BST", // test_tree_is_BST, diff --git a/tree.c b/tree.c index 24c20bc0e4321ab580d98f8699413807d51b12fc..bd7c7082cfaeeda5b59cec9f84f0ff46e3d3f21c 100644 --- a/tree.c +++ b/tree.c @@ -66,6 +66,27 @@ int bst_find_max(node_t *tree) } } + +node_t *bst_search(node_t *tree, int val) +{ + if(tree == NULL) + { + return NULL; + } + if(val == tree->val) + { + return tree; + } + if(val > tree->val) // Right + { + return bst_search(tree->right,val); + } + if(val < tree->val) // Left + { + return bst_search(tree->left,val); + } +} + void bst_destroy(node_t *tree) { if(tree == NULL){return;}