diff --git a/tests/test.c b/tests/test.c index 0d2eb54aec1fc0ff66ebc3c40d86cc20e1348d13..8ecab52e743fa072dcac2409f22e282ee1f02310 100644 --- a/tests/test.c +++ b/tests/test.c @@ -96,6 +96,46 @@ static MunitResult test_tree_is_present() return MUNIT_OK; } +static MunitResult test_tree_find_min() +{ + 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); + munit_assert_int32(bst_find_min(nd),==,2); + bst_destroy(nd); + return MUNIT_OK; +} + +static MunitResult test_tree_is_BST() +{ + node_t* nd = bst_create(); + nd = bst_insert(nd,12); // 12 + nd = bst_insert(nd,5); /* / \ */ // Not BST + nd = bst_insert(nd,32); // 5 32 + munit_assert_false(bst_is_bst(nd)); + bst_destroy(nd); + + nd = bst_create(); + nd = bst_insert(nd,12); // 12 + nd = bst_insert(nd,5); /* / */ + nd = bst_insert(nd,10); // 5 + /* / \ */ + // 10 + munit_assert_true(bst_is_bst(nd)); + bst_destroy(nd); + + + return MUNIT_OK; +} + static MunitTest test_suite_tests[] = { { @@ -146,6 +186,22 @@ static MunitTest test_suite_tests[] = { MUNIT_TEST_OPTION_NONE, NULL }, + { + (char*) "/test_tree_find_min", + test_tree_find_min, + NULL, + NULL, + MUNIT_TEST_OPTION_NONE, + NULL + }, + // { + // (char*) "/test_tree_is_BST", + // test_tree_is_BST, + // NULL, + // NULL, + // MUNIT_TEST_OPTION_NONE, + // NULL + // }, { NULL, NULL, NULL, NULL, MUNIT_TEST_OPTION_NONE, NULL } }; diff --git a/tree.c b/tree.c index ccd259e7e4012062ea275cc57e266e61cf4d4b1d..749182895fa8d01ec46a2b39f01e773e2a285fd8 100644 --- a/tree.c +++ b/tree.c @@ -9,8 +9,51 @@ node_t *bst_create() return NULL; } +bool bst_is_bst(node_t *tree) +{ + if(tree == NULL) // Default is true + { + return true; + } + if(tree->left != NULL) + { + if(tree->val < tree->left->val) // Is not BST + { + return false; + } + return bst_is_bst(tree->left); + } + if(tree->left != NULL) + { + if(tree->val > tree->right->val) // Is not BST + { + return false; + } + return bst_is_bst(tree->right); + } +} + + +int bst_find_min(node_t *tree) +{ + if(tree == NULL) + { + return INT_MIN; + } + if(tree->left != NULL) + { + return bst_find_min(tree->left); + } + else + { + return tree->val; + } +} + void bst_destroy(node_t *tree) { + if(tree == NULL){return;} + if(tree->left != NULL) { bst_destroy(tree->left); diff --git a/tree.h b/tree.h index fa9d80d7cd84c02cdc70ac99754868257d286fb6..2255ce725b5222651de2c53acf7fe1afd228b887 100644 --- a/tree.h +++ b/tree.h @@ -5,6 +5,7 @@ #include <stdlib.h> #include <stdint.h> #include <stdbool.h> +#include <limits.h> typedef struct _node_t { int val;