diff --git a/tests/test.c b/tests/test.c index cea1e8e48a88d5c7f0e3202ba51e9ca8a82381cd..e2b00f43e293f91a4364ca033660269aacd6796b 100644 --- a/tests/test.c +++ b/tests/test.c @@ -154,6 +154,44 @@ static MunitResult test_tree_search() return MUNIT_OK; } +static MunitResult test_tree_find_max_node() +{ + 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_int32(bst_find_max_node(nd)->val,==,50); + bst_destroy(nd); + return MUNIT_OK; +} + +static MunitResult test_tree_find_min_node() +{ + 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_int32(bst_find_min_node(nd)->val,==,2); + bst_destroy(nd); + return MUNIT_OK; +} + static MunitResult test_tree_is_BST() { node_t* nd = bst_create(); @@ -234,6 +272,14 @@ static MunitTest test_suite_tests[] = { MUNIT_TEST_OPTION_NONE, NULL }, + { + (char*) "/test_tree_find_min_node", + test_tree_find_min_node, + NULL, + NULL, + MUNIT_TEST_OPTION_NONE, + NULL + }, { (char*) "/test_tree_find_max", test_tree_find_max, @@ -242,6 +288,14 @@ static MunitTest test_suite_tests[] = { MUNIT_TEST_OPTION_NONE, NULL }, + { + (char*) "/test_tree_find_max_node", + test_tree_find_max_node, + NULL, + NULL, + MUNIT_TEST_OPTION_NONE, + NULL + }, { (char*) "/test_tree_search", test_tree_search, diff --git a/tree.c b/tree.c index bd7c7082cfaeeda5b59cec9f84f0ff46e3d3f21c..01d12bd7be38401f078b3005607edc5d123f4cd4 100644 --- a/tree.c +++ b/tree.c @@ -33,36 +33,49 @@ bool bst_is_bst(node_t *tree) } } - -int bst_find_min(node_t *tree) +node_t *bst_find_min_node(node_t *tree) { - if(tree == NULL) + node_t* tmp = tree; + if(tmp == NULL) { - return INT_MIN; + return NULL; } - if(tree->left != NULL) + if(tmp->left != NULL) { - return bst_find_min(tree->left); + return bst_find_min_node(tmp->left); } else { - return tree->val; + return tmp; } } +int bst_find_min(node_t *tree) +{ + node_t* tmp = bst_find_min_node(tree); + return (tmp != NULL)?tmp->val:INT_MIN; +} + int bst_find_max(node_t *tree) { - if(tree == NULL) + node_t* tmp = bst_find_max_node(tree); + return (tmp != NULL)?tmp->val:INT_MAX; +} + +node_t* bst_find_max_node(node_t *tree) +{ + node_t* tmp = tree; + if(tmp == NULL) { - return INT_MIN; + return NULL; } - if(tree->right != NULL) + if(tmp->right != NULL) { - return bst_find_max(tree->right); + return bst_find_max_node(tmp->right); } else { - return tree->val; + return tmp; } }