From d2a5a44b7f5e04176719b071ffa59430ba0ea945 Mon Sep 17 00:00:00 2001 From: poulpe <poulpe@localhost.localdomain> Date: Wed, 24 Mar 2021 16:00:19 +0100 Subject: [PATCH] [Update] Add bst_search + test --- tests/test.c | 28 ++++++++++++++++++++++++++++ tree.c | 21 +++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/tests/test.c b/tests/test.c index 8678185..cea1e8e 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 24c20bc..bd7c708 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;} -- GitLab