{"id":7015,"date":"2025-06-14T00:01:35","date_gmt":"2025-06-14T07:01:35","guid":{"rendered":"https:\/\/c-for-dummies.com\/blog\/?p=7015"},"modified":"2025-06-07T11:43:41","modified_gmt":"2025-06-07T18:43:41","slug":"searching-a-binary-tree","status":"publish","type":"post","link":"https:\/\/c-for-dummies.com\/blog\/?p=7015","title":{"rendered":"Searching a Binary Tree"},"content":{"rendered":"<p>As you might suspect, searching a binary search tree (BST) involves a recursive function. This function must plow through the tree, finding a value in a specific node. Because the BST is organized, the search process works far more quickly than when the data is unorganized or set in a sequential array. In fact, <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=6767\">the <em>bsearch()<\/em> function<\/a> uses a similar scheme requiring that the data first be sorted before the function works its magic.<br \/>\n<!--more--><br \/>\nContinuing from <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=6999\">last week&#8217;s Lesson<\/a>, I&#8217;ve replaced the <em>traverse()<\/em> function with a <em>search()<\/em> function. Its arguments are a node pointer and the value to look for:<\/p>\n<pre class=\"screen\">\r\n<span class=\"comments\">\/* search for a value *\/<\/span>\r\nstruct node *search(struct node *r, int v)\r\n{\r\n    <span class=\"comments\">\/* return on empty or when key found *\/<\/span>\r\n    if( r==NULL || r-&gt;key == v )\r\n        return(r);\r\n\r\n    <span class=\"comments\">\/* search for values less *\/<\/span>\r\n    if( v &lt; r-&gt;key )\r\n        return( search( r-&gt;left,v ) );\r\n    <span class=\"comments\">\/* search for values greater *\/<\/span>\r\n    return( search(r-&gt;right,v ) );\r\n}<\/pre>\n<p>The first <em>if<\/em> test is for both the NULL pointer and the proper value. When the NULL pointer is encountered, the search has reached the end of a branch (or whatever the proper term is). When the key value is found, the search is over. At either point, recursion unwinds, returning the value of either NULL (failure) or the desired node (success).<\/p>\n<p>The second <em>if<\/em> test plumbs the left node when the search value is less than the current node&#8217;s key value. The search is performed within the <em>return<\/em> statement, which is how the proper result &mdash; NULL or the found node &mdash; is returned to the calling statement.<\/p>\n<p>When the value of the current node is greater than the current&#8217;s node&#8217;s key value, the search goes to the right node. The result is returned directly (that recursion thing).<\/p>\n<p>The calling statement examines the returned result, either NULL for a failed search or the address of the node containing the matching key value.<\/p>\n<p>Here is the full code:<\/p>\n<h3><a href=\"https:\/\/github.com\/dangookin\/C-For-Dummies-Blog\/blob\/master\/2025_06_14-Lesson.c\" rel=\"noopener\" target=\"_blank\">2025_06_14-Lesson.c<\/a><\/h3>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n#include &lt;stdlib.h&gt;\r\n#include &lt;time.h&gt;\r\n\r\nstruct node {\r\n    int key;\r\n    struct node *left;\r\n    struct node *right;\r\n};\r\n\r\n<span class=\"comments\">\/* search for a value *\/<\/span>\r\nstruct node *search(struct node *r, int v)\r\n{\r\n    <span class=\"comments\">\/* return on empty or when key found *\/<\/span>\r\n    if( r==NULL || r-&gt;key == v )\r\n        return(r);\r\n\r\n    <span class=\"comments\">\/* search for values less *\/<\/span>\r\n    if( v &lt; r-&gt;key )\r\n        return( search( r-&gt;left,v ) );\r\n    <span class=\"comments\">\/* search for values greater *\/<\/span>\r\n    return( search(r-&gt;right,v ) );\r\n}\r\n\r\n<span class=\"comments\">\/* free the tree's node storage *\/<\/span>\r\nvoid free_tree(struct node *r)\r\n{\r\n    <span class=\"comments\">\/* stop on NULL *\/<\/span>\r\n    if( r==NULL )\r\n        return;\r\n\r\n    <span class=\"comments\">\/* plumb the depths *\/<\/span>\r\n    free_tree(r-&gt;left);\r\n    free_tree(r-&gt;right);\r\n    free(r);        <span class=\"comments\">\/* the (current) bottom node *\/<\/span>\r\n}\r\n\r\n<span class=\"comments\">\/* add a new node *\/<\/span>\r\nstruct node *add_node(struct node *r,int k)\r\n{\r\n\r\n    if( r==NULL )\r\n    <span class=\"comments\">\/* allocate a new node *\/<\/span>\r\n    {\r\n        r = malloc( sizeof(struct node) );\r\n        if( r==NULL )\r\n        {\r\n            fprintf(stderr,\"Unable to allocate memory\\n\");\r\n            exit(1);\r\n        }\r\n        r-&gt;key = k;        <span class=\"comments\">\/* set its key *\/<\/span>\r\n        r-&gt;right = NULL;\r\n        r-&gt;left = NULL;\r\n    }\r\n    else\r\n    {\r\n        <span class=\"comments\">\/* smaller values go on the left *\/<\/span>\r\n        if( k &lt; r-&gt;key )\r\n            r-&gt;left = add_node(r-&gt;left,k);\r\n        <span class=\"comments\">\/* larger values go on the right *\/<\/span>\r\n        else\r\n            r-&gt;right = add_node(r-&gt;right,k);\r\n    }\r\n    return(r);\r\n}\r\n\r\nint main()\r\n{\r\n    static int count = 9;\r\n    int data[] = {\r\n        50, 20, 85, 16, 41, 59, 96, 3, 68\r\n    };\r\n    struct node *root = NULL;\r\n    struct node *result;\r\n    int x,value;\r\n\r\n    <span class=\"comments\">\/* construct the tree *\/<\/span>\r\n    for( x=0; x&lt;count; x++ )\r\n        root = add_node(root,data[x]);\r\n\r\n    <span class=\"comments\">\/* search the tree *\/<\/span>\r\n    printf(\"Locate value: \");\r\n    scanf(\"%d\",&amp;value);\r\n    result = search(root,value);\r\n    if( result!=NULL )\r\n        printf(\"Value %d found\\n\",value);\r\n    else\r\n        printf(\"Value %d not found\\n\",value);\r\n\r\n    <span class=\"comments\">\/* clean-up *\/<\/span>\r\n    free_tree(root);\r\n    return 0;\r\n}<\/pre>\n<p>Obviously, more can be done with a Binary Search Tree beyond looking up simple values. The hurdle to clear from demonstration purposes is loading the tree with values.<\/p>\n<p>For example, I could set all kinds of interesting data to search, but with the data already written in the code it seems silly to then search for what&#8217;s already known. Even so, binary search trees represent an excellent way to organize and locate data. You find this type of structure implemented often in programming, which is why being familiar with its operation and coding is important to know.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The point of a binary search tree is to be able to search for data in the tree. <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=7015\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-7015","post","type-post","status-publish","format-standard","hentry","category-main"],"_links":{"self":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/7015","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=7015"}],"version-history":[{"count":3,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/7015\/revisions"}],"predecessor-version":[{"id":7027,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/7015\/revisions\/7027"}],"wp:attachment":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=7015"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=7015"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=7015"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}