<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Red-black tree &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/red-black-tree/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>on web development</description>
	<lastBuildDate>Tue, 13 Feb 2018 08:18:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.0.3</generator>
	<item>
		<title>Computer Algorithms: Binary Search Tree</title>
		<link>/2012/06/22/computer-algorithms-binary-search-tree-data-structure/</link>
		<comments>/2012/06/22/computer-algorithms-binary-search-tree-data-structure/#comments</comments>
		<pubDate>Fri, 22 Jun 2012 12:35:02 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[B-tree]]></category>
		<category><![CDATA[balanced binary search tree]]></category>
		<category><![CDATA[balanced binary search trees]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[Binary search tree]]></category>
		<category><![CDATA[binary search trees]]></category>
		<category><![CDATA[Binary trees]]></category>
		<category><![CDATA[Environment]]></category>
		<category><![CDATA[Extinction]]></category>
		<category><![CDATA[ineffective binary search trees]]></category>
		<category><![CDATA[Linked list]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[R-tree]]></category>
		<category><![CDATA[Red-black tree]]></category>
		<category><![CDATA[Scapegoat tree]]></category>
		<category><![CDATA[search operation]]></category>
		<category><![CDATA[search tree]]></category>
		<category><![CDATA[search trees]]></category>
		<category><![CDATA[sequential search]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[Tree]]></category>

		<guid isPermaLink="false">/?p=3196</guid>
		<description><![CDATA[Introduction Constructing a linked list is a fairly simple task. Linked lists are a linear structure and the items are located one after another, each pointing to its predecessor and its successor. Almost every operation is easy to code in few lines and doesn’t require advanced skills. Operations like insert, delete, etc. over linked lists &#8230; <a href="/2012/06/22/computer-algorithms-binary-search-tree-data-structure/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Binary Search Tree</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/08/24/computer-algorithms-finding-the-lowest-common-ancestor/" rel="bookmark" title="Computer Algorithms: Finding the Lowest Common Ancestor">Computer Algorithms: Finding the Lowest Common Ancestor </a></li>
<li><a href="/2012/07/03/computer-algorithms-balancing-a-binary-search-tree/" rel="bookmark" title="Computer Algorithms: Balancing a Binary Search Tree">Computer Algorithms: Balancing a Binary Search Tree </a></li>
<li><a href="/2010/09/29/construct-a-sorted-php-linked-list/" rel="bookmark" title="Construct a Sorted PHP Linked List">Construct a Sorted PHP Linked List </a></li>
<li><a href="/2012/06/14/computer-algorithms-linked-list-data-structure/" rel="bookmark" title="Computer Algorithms: Linked List">Computer Algorithms: Linked List </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Constructing a <a href="/2012/06/14/computer-algorithms-linked-list-data-structure/" title="Linked list">linked list</a> is a fairly simple task. Linked lists are a linear structure and the items are located one after another, each pointing to its predecessor and its successor. Almost every operation is easy to code in few lines and doesn’t require advanced skills. Operations like insert, delete, etc. over linked lists are performed in a linear time. Of course on small data sets this works fine, but as the data grows these operations, especially the search operation becomes too slow.</p>
<p>Indeed searching in a linked list has a linear complexity and in the worst case we must go through the entire list in order to find the desired element. The worst case is when the item doesn’t belong to the list and we must check every single item of the list even the last one without success. This approach seems much like the <a href="/2011/11/24/computer-algorithms-sequential-search/" title="the sequential search algorithm">sequential search</a> over arrays. Of course this is bad when we talk about large data sets. </p>
<p><figure id="attachment_3221" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/1.-Search-over-Linked-Lists-and-Arrays.png"><img src="/wp-content/uploads/2012/06/1.-Search-over-Linked-Lists-and-Arrays.png" alt="Search over Linked Lists and Arrays" title="Search over Linked Lists and Arrays" width="620" height="399" class="size-full wp-image-3221" srcset="/wp-content/uploads/2012/06/1.-Search-over-Linked-Lists-and-Arrays.png 620w, /wp-content/uploads/2012/06/1.-Search-over-Linked-Lists-and-Arrays-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Sequential search over arrays seems much like searching in linked lists and it is a basically ineffective opration!</figcaption></figure><span id="more-3196"></span></p>
<p>In terms of arrays, we could perform binary search and go directly in the middle of the array, then jump back or forward. That is because we can access array items directly using their index. However as we saw the linked lists unlike arrays can’t benefit of a direct access and we must go item by item.</p>
<p>Because of this natural problem of linked lists searching is slow and obviously we can’t make it better. The only way to improve searching over dynamic data structures is to use different data structure.</p>
<p>The tree is a data structure where each item, except of keeping some data, keeps a reference (pointer) to its children and its parent.</p>
<figure id="attachment_3223" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/2.-A-tree.png"><img src="/wp-content/uploads/2012/06/2.-A-tree.png" alt="A tree" title="A tree" width="620" height="399" class="size-full wp-image-3223" srcset="/wp-content/uploads/2012/06/2.-A-tree.png 620w, /wp-content/uploads/2012/06/2.-A-tree-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">A tree data structure. Each item points to its parent and its children. However the root&#8217;s parent it&#8217;s NIL.</figcaption></figure>
<p>Of course if the item doesn’t have children, they are NIL, then this is considered a leaf in the tree terminology. In the other hand if the item doesn’t have parent item it is considered the root.</p>
<figure id="attachment_3226" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/3.-Root-and-Leafs.png"><img src="/wp-content/uploads/2012/06/3.-Root-and-Leafs.png" alt="Root and Leafs" title="Root and Leafs" width="620" height="399" class="size-full wp-image-3226" srcset="/wp-content/uploads/2012/06/3.-Root-and-Leafs.png 620w, /wp-content/uploads/2012/06/3.-Root-and-Leafs-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Root and Leafs</figcaption></figure>
<p>If there is no item in the tree the tree is considered empty. </p>
<p>In these terms only the root has no parent, and each item can have as many children as possible. Here are some trees in form of a diagrams.</p>
<figure id="attachment_3227" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/4.-Trees.png"><img src="/wp-content/uploads/2012/06/4.-Trees.png" alt="Trees" title="Trees" width="620" height="399" class="size-full wp-image-3227" srcset="/wp-content/uploads/2012/06/4.-Trees.png 620w, /wp-content/uploads/2012/06/4.-Trees-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Possible trees</figcaption></figure>
<p>If we’re looking at the root of the tree we can assume there are two sub-trees &#8211; one left and one right. However if we isolate only one of these sub-trees we can again think of it as a tree and assume that it has one left and one right sub-trees and go recursively with this definition.</p>
<figure id="attachment_3228" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/5.-Sub-trees.png"><img src="/wp-content/uploads/2012/06/5.-Sub-trees.png" alt="Sub-trees" title="Sub-trees" width="620" height="399" class="size-full wp-image-3228" srcset="/wp-content/uploads/2012/06/5.-Sub-trees.png 620w, /wp-content/uploads/2012/06/5.-Sub-trees-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Left and right sub-trees</figcaption></figure>
<h2>Overview</h2>
<p>A binary tree is a tree where each item can have at most two children. </p>
<figure id="attachment_3230" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/6.-Binary-Tree.png"><img src="/wp-content/uploads/2012/06/6.-Binary-Tree.png" alt="Binary Tree" title="Binary Tree" width="620" height="399" class="size-full wp-image-3230" srcset="/wp-content/uploads/2012/06/6.-Binary-Tree.png 620w, /wp-content/uploads/2012/06/6.-Binary-Tree-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">In the binary tree each node has at most two sub-trees &#8211; left and right!</figcaption></figure>
<p>Binary trees are especially important because they can contain ordered data in a specific manner. Building a binary tree isn’t difficult at all and it’s very similar to building a linked list.<br />
However a binary tree isn’t more successful in searching than any other tree or data structure. If the items aren’t placed in a specific order we must go through the entire tree in order to find the searched item. This isn’t a great optimization, so we must put an order in it to improve the searching process.</p>
<h3>Binary Search Tree</h3>
<p>The binary search tree is a specific kind of binary tree, where the each item keeps greater elements on the right, while the smaller items are on the left. </p>
<figure id="attachment_3233" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/7.-Binary-search-tree.png"><img src="/wp-content/uploads/2012/06/7.-Binary-search-tree.png" alt="Binary search tree" title="Binary search tree" width="620" height="399" class="size-full wp-image-3233" srcset="/wp-content/uploads/2012/06/7.-Binary-search-tree.png 620w, /wp-content/uploads/2012/06/7.-Binary-search-tree-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Binary search tree &#8211; BST</figcaption></figure>
<p>Constructing a binary search tree is easy, because we can go for inserting each item only by comparing it with the root and decide where to go (left or right) based on its value. </p>
<figure id="attachment_3234" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/8.-Insert-in-BST.png"><img src="/wp-content/uploads/2012/06/8.-Insert-in-BST.png" alt="Insert in BST" title="Insert in BST" width="620" height="399" class="size-full wp-image-3234" srcset="/wp-content/uploads/2012/06/8.-Insert-in-BST.png 620w, /wp-content/uploads/2012/06/8.-Insert-in-BST-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Inserting in a binary search tree is fairly easy</figcaption></figure>
<h2>Implementation</h2>
<p>The following code in <a href="/category/php/" title="PHP articles in stoimen.com">PHP</a> describes the basic principles of a binary search tree.</p>
<pre lang="PHP">
class Node
{
	public $parent = null;
	public $left = null;
	public $right = null;
	public $data = null;
	
	public function __construct($data)
	{
		$this->data = $data;
	}
	
	public function __toString()
	{
		return $this->data;
	}
}

class BinaryTree
{
	protected $_root = null;
	
	protected function _insert(&$new, &$node)
	{
		if ($node == null) {
			$node = $new;
			return;
		}
		
		if ($new->data <= $node->data) {
			if ($node->left == null) {
				$node->left = $new;
				$new->parent = $node;
			} else {
				$this->_insert($new, $node->left);
			}
		} else {
			if ($node->right == null) {
				$node->right = $new;
				$new->parent = $node;
			} else {
				$this->_insert($new, $node->right);
			}
		}		
	}
	
	protected function _search(&$target, &$node)
	{
		if ($target == $node) {
			return 1;
		} else if ($target->data > $node->data && isset($node->right)) {
			return $this->_search($target, $node->right);
		} else if ($target->data <= $node->data && isset($node->left)) {
			return $this->_search($target, $node->left);
		}
		
		return 0;
	}
	
	public function insert($node)
	{
		$this->_insert($node, $this->_root);
	}
	
	public function search($item) 
	{
		return $this->_search($item, $this->_root);
	}
}

$a = new Node(3);
$b = new Node(2);
$c = new Node(4);
$d = new Node(7);
$e = new Node(6);

$t = new BinaryTree();

$t->insert($a);
$t->insert($b);
$t->insert($c);
$t->insert($d);
$t->insert($e);

echo $t->search($e);
</pre>
<h2>Search Complexity</h2>
<p>Searching in binary search trees is supposed to be faster than searching into linked list. However the searching process in a BST can be very fast, but also can be as slow as on linked list. That is because depending on the input of items they can be placed only on the one side of the root.</p>
<figure id="attachment_3236" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/9.-Tree-or-a-Linked-list.png"><img src="/wp-content/uploads/2012/06/9.-Tree-or-a-Linked-list.png" alt="Tree or a Linked list" title="Tree or a Linked list" width="620" height="399" class="size-full wp-image-3236" srcset="/wp-content/uploads/2012/06/9.-Tree-or-a-Linked-list.png 620w, /wp-content/uploads/2012/06/9.-Tree-or-a-Linked-list-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">By inserting only greater items there are only right sub-trees &#8211; the tree isn&#8217;t different from a linked list and the searching is slow!</figcaption></figure>
<p>That makes the worst-case searching as slow as on linked list which is linear O(n). However if the tree is somehow balanced we can search very quickly with O(log(n)) time.</p>
<a href="/wp-content/uploads/2012/06/BST-Chart.png"><img src="/wp-content/uploads/2012/06/BST-Chart.png" alt="BST Chart" title="BST Chart" width="600" height="371" class="size-full wp-image-3238" srcset="/wp-content/uploads/2012/06/BST-Chart.png 600w, /wp-content/uploads/2012/06/BST-Chart-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a>
<h3>Further Optimization</h3>
<p>We now see how ineffective binary search trees can be, so the only thing we must care is how to keep them balanced, so the search will be faster. The answer is to maintain (during insertion) a balanced binary search tree, which is another very handy data structure. </p>
<p>A balanced binary search tree, or only balanced tree, is a data structure where the height of left and the right sub-trees can vary by one level at most. </p>
<figure id="attachment_3237" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/10.-Balanced-or-not.png"><img src="/wp-content/uploads/2012/06/10.-Balanced-or-not.png" alt="Balanced or not" title="Balanced or not" width="620" height="399" class="size-full wp-image-3237" srcset="/wp-content/uploads/2012/06/10.-Balanced-or-not.png 620w, /wp-content/uploads/2012/06/10.-Balanced-or-not-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Searching in a balanced tree is significantly faster than in some binary search trees!</figcaption></figure>
<h2>Application</h2>
<p>Binary search trees are easy to build and maintain. The great thing is that if the data is well balanced they can be very useful for searching. The only problem is that these structures can be ineffective depending on the insertion order. However if we are somehow sure that the items aren’t ordered on the input, we may expect some optimized searching compared to a linked list. Compared to balanced binary search trees, BST require much less time to build and maintain (insert, delete).</p>
<p>Trees are very useful when working with graphs. Actually one of the very common tasks is walking through the entire tree, which can be done in several ways. First we can go to the left sub-tree, then the root and then the right sub-tree. Or right-root-left. Or root-left-right. </p>
<p>However we can go in depth first often called depth-first-search or a breadth-first-search.</p>
<p>These two methods are designed to walk through the items in a specific order, which is very handy for some specific tasks &#8211; at least each tree is also a graph.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/08/24/computer-algorithms-finding-the-lowest-common-ancestor/" rel="bookmark" title="Computer Algorithms: Finding the Lowest Common Ancestor">Computer Algorithms: Finding the Lowest Common Ancestor </a></li>
<li><a href="/2012/07/03/computer-algorithms-balancing-a-binary-search-tree/" rel="bookmark" title="Computer Algorithms: Balancing a Binary Search Tree">Computer Algorithms: Balancing a Binary Search Tree </a></li>
<li><a href="/2010/09/29/construct-a-sorted-php-linked-list/" rel="bookmark" title="Construct a Sorted PHP Linked List">Construct a Sorted PHP Linked List </a></li>
<li><a href="/2012/06/14/computer-algorithms-linked-list-data-structure/" rel="bookmark" title="Computer Algorithms: Linked List">Computer Algorithms: Linked List </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/06/22/computer-algorithms-binary-search-tree-data-structure/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
