{"id":4797,"date":"2015-02-23T10:45:52","date_gmt":"2015-02-23T18:45:52","guid":{"rendered":"https:\/\/blog.digilentinc.com\/?p=4797"},"modified":"2025-06-02T03:40:27","modified_gmt":"2025-06-02T10:40:27","slug":"binary-search-trees","status":"publish","type":"post","link":"https:\/\/digilent.com\/blog\/binary-search-trees\/","title":{"rendered":"Binary Search Trees: Functions &#038; Insertion Explained"},"content":{"rendered":"<p>The binary search tree (BST) is a data structure that is much different from the other structures that we&#8217;ve gone over so far. Unlike stacks, queues, and lists, a BST&#8217;s struct is not a &#8220;straight-line&#8221;. Each node in a BST has a left and right child node.<\/p>\n<figure id=\"attachment_4970\" aria-describedby=\"caption-attachment-4970\" style=\"width: 399px\" class=\"wp-caption alignnone\"><a href=\"https:\/\/digilent.com\/blog\/wp-content\/uploads\/2015\/01\/tree.png\"><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-4970\" src=\"https:\/\/digilent.com\/blog\/wp-content\/uploads\/2015\/01\/tree.png\" alt=\"A Binary Search Tree\" width=\"399\" height=\"329\" srcset=\"https:\/\/digilent.com\/blog\/wp-content\/uploads\/2015\/01\/tree.png 399w, https:\/\/digilent.com\/blog\/wp-content\/uploads\/2015\/01\/tree-225x186.png 225w\" sizes=\"auto, (max-width: 399px) 100vw, 399px\" \/><\/a><figcaption id=\"caption-attachment-4970\" class=\"wp-caption-text\">A binary search tree.<\/figcaption><\/figure>\n<p>&nbsp;<\/p>\n<p>The BST above is a classic example of how BSTs work. &#8220;10&#8221; is the first node in the tree, and then all the other nodes are put in the tree. We&#8217;re going to make an unbalanced search tree today, and with the exception of deleting nodes, the location of nodes won&#8217;t change. A balanced search tree, which we won&#8217;t go over today, moves nodes around in tree to keep balance.<\/p>\n<p>&nbsp;<\/p>\n<p>There are four main functions of a BST:<br \/>\n1. Insert. Due to the nature of BSTs, the insert function will create a new <em>leaf<\/em> (a bottom node of the tree).<br \/>\n2. Find functions (findMin, findMax, and contains). The find function\u00a0is very similar to insert\u00a0and\u00a0will go down the tree until the value is found.<br \/>\n3. Remove. Remove deletes a node. This is most complicated function in a BST, as there are three different cases (we will go over these).<br \/>\n4. Print. There are three ways to print a BSTs that we will go over in this post. Each one prints the nodes out in a different order.<br \/>\nWhat makes a binary search tree so interesting is that the insert, find, and delete functions all have an average complexity of O(log n). When those functions are called, each iteration will reduce the number of &#8220;n&#8221; values that are left to search through by half, leading to O(log n) complexity. An easy example is search, where if we search for &#8220;14&#8221; in the BST above, the first iteration will take us to 11, removing the entire left half of the BST.<br \/>\nNow that BSTs have been introduced, let&#8217;s get into their implementation. It&#8217;s important to note that our BST won&#8217;t support duplicates, but that is definitely a feature you can add! We won&#8217;t go over the main and header files, most they are pretty close to the same as in the stacks and queues blog post. Check them out here: <a href=\"https:\/\/digilent.com\/blog\/wp-content\/uploads\/2015\/01\/header1.txt\"><strong>header<\/strong><\/a> and <a href=\"https:\/\/digilent.com\/blog\/wp-content\/uploads\/2015\/01\/main1.txt\"><strong>main<\/strong><\/a>.<\/p>\n<p>&nbsp;<\/p>\n<p>1. Insert<\/p>\n<figure id=\"attachment_5142\" aria-describedby=\"caption-attachment-5142\" style=\"width: 412px\" class=\"wp-caption alignnone\"><a href=\"https:\/\/digilent.com\/blog\/wp-content\/uploads\/2015\/01\/insert.png\"><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-5142\" src=\"https:\/\/digilent.com\/blog\/wp-content\/uploads\/2015\/01\/insert.png\" alt=\"Insert into Tree\" width=\"412\" height=\"399\" srcset=\"https:\/\/digilent.com\/blog\/wp-content\/uploads\/2015\/01\/insert.png 412w, https:\/\/digilent.com\/blog\/wp-content\/uploads\/2015\/01\/insert-225x218.png 225w\" sizes=\"auto, (max-width: 412px) 100vw, 412px\" \/><\/a><figcaption id=\"caption-attachment-5142\" class=\"wp-caption-text\">Insert into tree.<\/figcaption><\/figure>\n<p>You can see there are two insert functions. The first function is just calling the second function. This may seem a little confusing, but due to recursive calls, this makes it easier to call in main.<\/p>\n<p>&nbsp;<\/p>\n<p>In insert, there are four cases. The first is our base case, we create a new node, assign the element value to our entry, then assign the left and right nodes to NULL. Our second and third cases are our recursive calls, these two move the the element farther down the tree. If the element is less than the value in the current branch, we send it left, but otherwise we&#8217;ll send it right. These two statements are what make BSTs interesting. Other data structures&#8217; insert functions are linear, but the BST&#8217;s insert has multiple options.<\/p>\n<p>&nbsp;<\/p>\n<p>2. findMin, findMax, and contains<\/p>\n<figure id=\"attachment_5158\" aria-describedby=\"caption-attachment-5158\" style=\"width: 488px\" class=\"wp-caption alignnone\"><a href=\"https:\/\/digilent.com\/blog\/wp-content\/uploads\/2015\/01\/findmax.png\"><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-5158\" src=\"https:\/\/digilent.com\/blog\/wp-content\/uploads\/2015\/01\/findmax.png\" alt=\"Search functions\" width=\"488\" height=\"583\" srcset=\"https:\/\/digilent.com\/blog\/wp-content\/uploads\/2015\/01\/findmax.png 488w, https:\/\/digilent.com\/blog\/wp-content\/uploads\/2015\/01\/findmax-188x225.png 188w\" sizes=\"auto, (max-width: 488px) 100vw, 488px\" \/><\/a><figcaption id=\"caption-attachment-5158\" class=\"wp-caption-text\">Search functions.<\/figcaption><\/figure>\n<p>&nbsp;<\/p>\n<p>These functions are all very similar, but each has a\u00a0different purpose. Contains is a boolean function, and it goes through the tree\u00a0to\u00a0return &#8220;true&#8221; if the value is found. Functions findMin and findMax are essential &#8220;mirrored&#8221; functions. FindMin goes to the left node of each branch until the last left node is reached &#8212; this is the smallest value&#8211; and then this node is returned. FindMax goes through all the right nodes until the end is reached, then returns the largest value node.<\/p>\n<p>&nbsp;<\/p>\n<p>3. Remove<\/p>\n<figure id=\"attachment_5163\" aria-describedby=\"caption-attachment-5163\" style=\"width: 581px\" class=\"wp-caption alignnone\"><a href=\"https:\/\/digilent.com\/blog\/wp-content\/uploads\/2015\/01\/remove.png\"><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-5163\" src=\"https:\/\/digilent.com\/blog\/wp-content\/uploads\/2015\/01\/remove.png\" alt=\"Remove from Tree\" width=\"581\" height=\"405\" srcset=\"https:\/\/digilent.com\/blog\/wp-content\/uploads\/2015\/01\/remove.png 581w, https:\/\/digilent.com\/blog\/wp-content\/uploads\/2015\/01\/remove-225x157.png 225w\" sizes=\"auto, (max-width: 581px) 100vw, 581px\" \/><\/a><figcaption id=\"caption-attachment-5163\" class=\"wp-caption-text\">Remove from tree.<\/figcaption><\/figure>\n<p>&nbsp;<\/p>\n<p>Remove is easily the most complicated function of a Binary Search Tree. There are three separate cases for remove.<br \/>\nThe first is when the node to be removed has no children. This is the easiest case, wherein we just delete the node.<br \/>\nThe second case is when the node to be removed has one child. This case isn&#8217;t extremely difficult either, as we assign the child of the node to be removed to the original node&#8217;s location and then delete the old node. The last case is easily the most complicated, when the node has two children. In order for us to ensure the integrity of our BST, we must replace the node to be removed with a value that doesn&#8217;t how the binary search tree works. For us to do this, we need to pick the smallest node on the right child&#8217;s subtree. This is the only node that will ensure that the tree&#8217;s integrity isn&#8217;t changed. Here is where our findMin function is useful, we call findMin on the right node, and assign that value to the node to be deleted. We then &#8220;move&#8221; the node we found to the location of the node to be deleted, then we update the tree accordingly (as duplicates aren&#8217;t allowed).<\/p>\n<p>&nbsp;<\/p>\n<p>4. Print Functions<\/p>\n<p><a href=\"https:\/\/digilent.com\/blog\/wp-content\/uploads\/2015\/01\/newprint.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium wp-image-5173\" src=\"https:\/\/digilent.com\/blog\/wp-content\/uploads\/2015\/01\/newprint-273x600.png\" alt=\"newprint\" width=\"273\" height=\"600\" srcset=\"https:\/\/digilent.com\/blog\/wp-content\/uploads\/2015\/01\/newprint-273x600.png 273w, https:\/\/digilent.com\/blog\/wp-content\/uploads\/2015\/01\/newprint-102x225.png 102w, https:\/\/digilent.com\/blog\/wp-content\/uploads\/2015\/01\/newprint.png 442w\" sizes=\"auto, (max-width: 273px) 100vw, 273px\" \/><\/a><\/p>\n<p>&nbsp;<\/p>\n<p>Binary Search Trees can be printed out in three ways: PreOrder, PostOrder, and InOrder. All these functions have a &#8220;cout&#8221; call and two recursive calls, that is basically all that the print functions are.<\/p>\n<p>&nbsp;<\/p>\n<p>PreOrder prints out the value of node before calling node-&gt;left and node-&gt;right. This prints out the left side of a tree, then the right side of the tree.<\/p>\n<p>&nbsp;<\/p>\n<p>PostOrder prints out the values of node-&gt;left and node-&gt;right, then prints out the value of the node. Because this is a recursive call, it will print out all the leaf nodes, and then print out the branches.<\/p>\n<p>&nbsp;<\/p>\n<p>InOrder is fairly\u00a0simple. By printing out the node value in between calling the node-&gt;left and node-&gt;right, we print out the tree in order.<\/p>\n<div class='watch-action'><div class='watch-position align-left'><div class='action-like'><a class='lbg-style6 like-4797 jlk' data-task='like' data-post_id='4797' data-nonce='aa9e7f9f96' rel='nofollow'><img src='https:\/\/digilent.com\/blog\/wp-content\/plugins\/wti-like-post-pro\/images\/pixel.gif' title='Like' \/><span class='lc-4797 lc'>0<\/span><\/a><\/div><div class='action-unlike'><a class='unlbg-style6 unlike-4797 jlk' data-task='unlike' data-post_id='4797' data-nonce='aa9e7f9f96' rel='nofollow'><img src='https:\/\/digilent.com\/blog\/wp-content\/plugins\/wti-like-post-pro\/images\/pixel.gif' title='Unlike' \/><span class='unlc-4797 unlc'>0<\/span><\/a><\/div><\/div> <div class='status-4797 status align-left'>Be the 1st to vote.<\/div><\/div><div class='wti-clear'><\/div>","protected":false},"excerpt":{"rendered":"<p>The binary search tree (BST) is a data structure that is much different from the other structures that we&#8217;ve gone over so far. Unlike stacks, queues, and lists, a BST&#8217;s struct is not a &#8220;straight-line&#8221;. Each node in a BST has a left and right child node.<\/p>\n","protected":false},"author":29,"featured_media":4970,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1563],"tags":[],"ppma_author":[4478],"class_list":["post-4797","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-guide"],"jetpack_featured_media_url":"https:\/\/digilent.com\/blog\/wp-content\/uploads\/2015\/01\/tree.png","authors":[{"term_id":4478,"user_id":29,"is_guest":0,"slug":"josh-woldstad","display_name":"Josh","avatar_url":"https:\/\/secure.gravatar.com\/avatar\/b4b62729a3daba9bb76117db7130e81e?s=96&d=mm&r=g","author_category":"","user_url":"","last_name":"Woldstad","last_name_2":"","first_name":"Josh","first_name_2":"","job_title":"","description":"I love Coding!"}],"post_mailing_queue_ids":[],"_links":{"self":[{"href":"https:\/\/digilent.com\/blog\/wp-json\/wp\/v2\/posts\/4797","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/digilent.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/digilent.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/digilent.com\/blog\/wp-json\/wp\/v2\/users\/29"}],"replies":[{"embeddable":true,"href":"https:\/\/digilent.com\/blog\/wp-json\/wp\/v2\/comments?post=4797"}],"version-history":[{"count":3,"href":"https:\/\/digilent.com\/blog\/wp-json\/wp\/v2\/posts\/4797\/revisions"}],"predecessor-version":[{"id":31615,"href":"https:\/\/digilent.com\/blog\/wp-json\/wp\/v2\/posts\/4797\/revisions\/31615"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/digilent.com\/blog\/wp-json\/wp\/v2\/media\/4970"}],"wp:attachment":[{"href":"https:\/\/digilent.com\/blog\/wp-json\/wp\/v2\/media?parent=4797"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/digilent.com\/blog\/wp-json\/wp\/v2\/categories?post=4797"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/digilent.com\/blog\/wp-json\/wp\/v2\/tags?post=4797"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/digilent.com\/blog\/wp-json\/wp\/v2\/ppma_author?post=4797"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}