<?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>Scapegoat tree &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/scapegoat-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: Balancing a Binary Search Tree</title>
		<link>/2012/07/03/computer-algorithms-balancing-a-binary-search-tree/</link>
		<comments>/2012/07/03/computer-algorithms-balancing-a-binary-search-tree/#comments</comments>
		<pubDate>Tue, 03 Jul 2012 13:30:35 +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 search tree]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[Binary search algorithm]]></category>
		<category><![CDATA[Binary search tree]]></category>
		<category><![CDATA[binary search trees]]></category>
		<category><![CDATA[Binary trees]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Discrete mathematics]]></category>
		<category><![CDATA[Environment]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[NIL]]></category>
		<category><![CDATA[non-balanced binary search]]></category>
		<category><![CDATA[non-balanced search trees]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Scapegoat tree]]></category>
		<category><![CDATA[search tree]]></category>
		<category><![CDATA[Self-balancing binary search tree]]></category>
		<category><![CDATA[Splay tree]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[Tree]]></category>

		<guid isPermaLink="false">/?p=3220</guid>
		<description><![CDATA[Introduction The binary search tree is a very useful data structure, where searching can be significantly faster than searching into a linked list. However in some cases searching into a binary tree can be as slow as searching into a linked list and this mainly depends on the input sequence. Indeed in case the input &#8230; <a href="/2012/07/03/computer-algorithms-balancing-a-binary-search-tree/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Balancing a 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/06/22/computer-algorithms-binary-search-tree-data-structure/" rel="bookmark" title="Computer Algorithms: Binary Search Tree">Computer Algorithms: 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="/2011/12/26/computer-algorithms-binary-search/" rel="bookmark" title="Computer Algorithms: Binary Search">Computer Algorithms: Binary Search </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>The <a href="/2012/06/22/computer-algorithms-binary-search-tree-data-structure/" title="Computer Algorithms: Binary Search Tree">binary search tree</a> is a very useful data structure, where searching can be significantly faster than searching into a linked list. However in some cases searching into a binary tree can be as slow as searching into a linked list and this mainly depends on the input sequence. Indeed in case the input is sorted the binary tree will seem much like a linked list and the search will be slow. </p>
<figure id="attachment_3244" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/07/1.-Inserting-into-a-binary-search-tree.png"><img src="/wp-content/uploads/2012/07/1.-Inserting-into-a-binary-search-tree.png" alt="Inserting into a binary search tree" title="Inserting into a binary search tree" width="620" height="399" class="size-full wp-image-3244" srcset="/wp-content/uploads/2012/07/1.-Inserting-into-a-binary-search-tree.png 620w, /wp-content/uploads/2012/07/1.-Inserting-into-a-binary-search-tree-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">A binary search tree may seem much like a linked lists if the input is nearly sorted!</figcaption></figure>
<p>To overcome this we must change a bit the data structure in order to stay well balanced. It’s intuitively clear that the searching process will be better if the tree is well branched. This is when finding an item will become faster with minimal effort.</p>
<figure id="attachment_3246" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/07/2.-Balanced-tree.png"><img src="/wp-content/uploads/2012/07/2.-Balanced-tree.png" alt="Balanced tree" title="Balanced tree" width="620" height="399" class="size-full wp-image-3246" srcset="/wp-content/uploads/2012/07/2.-Balanced-tree.png 620w, /wp-content/uploads/2012/07/2.-Balanced-tree-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Searching into a balanced tree is significantly faster than searching into a non-balanced tree!</figcaption></figure>
<p>Since we know how to construct a binary search tree the only thing left is to keep it balanced. Obviously we will need to re-balance the tree on each insert and delete, which will make this data structure more difficult to maintain compared to non-balanced search trees, but searching into it will be significantly faster.<span id="more-3220"></span></p>
<h2>Overview</h2>
<p>In order to balance a tree we can go for the very basic and intuitive approach. First let’s take a look of one non-balanced tree.</p>
<a href="/wp-content/uploads/2012/07/3.-Balanced-vs.-Non-Balanced.png"><img src="/wp-content/uploads/2012/07/3.-Balanced-vs.-Non-Balanced.png" alt="Balanced vs. Non-Balanced" title="Balanced vs. Non-Balanced" width="620" height="399" class="size-full wp-image-3247" srcset="/wp-content/uploads/2012/07/3.-Balanced-vs.-Non-Balanced.png 620w, /wp-content/uploads/2012/07/3.-Balanced-vs.-Non-Balanced-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a>
<p>Compared to the balanced tree on the right from the image above with the same items we see that the root is approximately equal to its middle item. I.e. 4 is the middle item of the sequence [1,2,3,4,5,6,7]!</p>
<p>If we take a look of the sequence [2 3 4], clearly by building a binary tree it will look like a linked list. However if we choose the middle item for a root &#8211; we’ll easy build a balanced tree. So the only thing to do is to get the middle item out of a list.</p>
<p>We now see that building a balanced binary tree out of a sorted linked list isn’t that difficult. In the other hand, as I said above, on each insert we’ll have to rebalance the tree. You can think of the tree out of the values [1,2,3,4,5] and the same tree after inserting [44,45,46,47,48]. Clearly the root of the resulting tree will no longer be 3. </p>
<p>So we need to implement the re-balancing in three basic operations. First we need to build a linked list out of a balanced binary tree. On the second place we’ll have to find the middle item and on the third place we’ll have to build again a balanced search tree. </p>
<p>Hopefully the first two tasks are easy to implement, because making out a sorted list out of a binary search tree is very easy. We need just to walk through the tree from left-root-right recursively. Because smaller items are in the left sub-tree and greater items are on the right we’re sure that the resulting list will be sorted. Then finding the middle item is as easy as finding the middle index of an array know its length.</p>
<h2>Balancing Optimization</h2>
<p>Of course the main problem of re-balancing a tree on each insert/delete is that this operations will be slow and soon or later we’ll have problems. That can happen if we change often our data structure. That’s why we should think of some optimization. </p>
<p>Normally we insert and re-balance on each step, which is slow. In the other hand we can do bulk insert forgetting about the re-balancing for a while. Only after the inserts are done we can go for re-balancing the entire tree.</p>
<figure id="attachment_3249" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/07/4.-Bulk-Insert-with-Only-one-Balance.png"><img src="/wp-content/uploads/2012/07/4.-Bulk-Insert-with-Only-one-Balance.png" alt="Bulk Insert with Only one Balance" title="Bulk Insert with Only one Balance" width="620" height="399" class="size-full wp-image-3249" srcset="/wp-content/uploads/2012/07/4.-Bulk-Insert-with-Only-one-Balance.png 620w, /wp-content/uploads/2012/07/4.-Bulk-Insert-with-Only-one-Balance-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Doing bulk insert/delete and only one balancing will make the data structure faster!</figcaption></figure>
<p>The same approach we can use with bulk delete. We can just set to NIL the items we want to delete, but we can keep them in memory for a while. Thus the search will stay relatively fast without rebalancing the tree. However this approach can be used carefully because we’ll keep some data in the memory without actually using it. </p>
<figure id="attachment_3250" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/07/5.-Bulk-Delete.png"><img src="/wp-content/uploads/2012/07/5.-Bulk-Delete.png" alt="Bulk Delete" title="Bulk Delete" width="620" height="399" class="size-full wp-image-3250" srcset="/wp-content/uploads/2012/07/5.-Bulk-Delete.png 620w, /wp-content/uploads/2012/07/5.-Bulk-Delete-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">We can NULL items without actually removing the pointers (links) and the structure of the tree!</figcaption></figure>
<h2>Implementation</h2>
<p>Implementing balanced binary trees is more difficult than just implementing binary search trees. Here’s an example in <a href="/category/php/" title="PHP on stoimen.com">PHP</a>.</p>
<pre lang="PHP">
class Node
{
	protected   $_parent = null;
	protected   $_left = null;
	protected   $_right = null;
	protected   $_key;
    protected   $_data = null;
	
    /**
     * @param int $key
     * @param mixed $data 
     */
	public function __construct($key, $data)
	{
		$this->_key = $key;
        $this->_data = $data;
	}
    
    /**
     * Empty the node by keeping up the key, but
     * setting up the data to NULL 
     */
    public function doEmpty() 
    {
        $this->_data = null;
    }
	
    /**
     * Print the key
     * 
     * @return string
     */
	public function __toString()
	{
		return 'First name: ' . $this->_data['f_name']
                . '<br />'
                . 'Last name: ' . $this->_data['l_name']
                . '<br />' 
                . 'Birthday: ' . $this->_data['b_day'];
	}
    
    public function &getParent() { return $this->_parent; }
    public function setParent($parent) { $this->_parent = $parent; }
    
    public function &getLeft() { return $this->_left; }
    public function setLeft($left) { $this->_left = $left; }
    
    public function &getRight() { return $this->_right; }
    public function setRight($right) { $this->_right = $right; }
    
    public function &getKey() { return $this->_key; }
    public function setKey($key) { $this->_key = $key; }
    
    public function &getData() { return $this->_data; }
    public function setData($data) { $this->_data = $data; }
}

class BalancedBinaryTree
{
    /**
     * Reference to the root tree
     * 
     * @var Node 
     */
	protected $_root = null;
	
    /**
     * @param type $new
     * @param type $node
     * @return type 
     */
	protected function _insert($new, &$root)
	{
        // in case the tree is empty
        // make the new node the root of
        // the tree
		if ($root == null) {
			$root = $new;
			return;
		}
		
		if ($new->getKey() <= $root->getKey()) {
			if ($root->getLeft() == null) {
				$root->setLeft($new);
				$new->setParent($root);
			} else {
				$this->_insert($new, $root->getLeft());
			}
		} else {
			if ($root->getRight() == null) {
				$root->setRight($new);
				$new->setParent($root);
			} else {
				$this->_insert($new, $root->getRight());
			}
		}		
	}
	
    /**
     * FALSE on not found
     * 
     * @param string $firstName
     * @param BalancedBinaryTree $tree
     * @return boolean 
     */
	protected function _search($firstName, &$tree)
	{
        if ($tree == null) {
            return FALSE;
        }

        $data = $tree->getData();
		
        if ($firstName == $data['f_name']) {
			return $tree;
		}
        
        // search the left sub-tree
        return $this->_search($firstName, $tree->getLeft())
                . $this->_search($firstName, $tree->getRight());
	}
    
    /**
     *
     * @param int $key
     * @param Node $tree
     * @return FALSE or Node 
     */
    protected function _searchByKey($key, &$tree)
    {
        if ($tree == null) {
            return FALSE;
        }
        
        if ($tree->getKey() == $key) {
            return $tree;
        } else if ($tree->getKey() > $key) {
            return $this->_searchByKey($key, $tree->getLeft());
        } else {
            return $this->_searchByKey($key, $tree->getRight());
        }
    }
    
    /**
     * Returns a list out of the tree by emptying the tree. 
     * In other way the tree and the list will allocate memory
     * 
     * @param BalancedBinaryTree $tree 
     */
    protected function _leftRootRight($tree)
    {
        if ($tree == null) {
            return array();
        }
        
        return array_merge(
                $this->_leftRootRight($tree->getLeft()),
                array(array('key' => $tree->getKey(), 'data' => $tree->getData())),
                $this->_leftRootRight($tree->getRight()));
    }
    
    public function _balance($list)
    {
        if (empty($list)) {
            return;
        }
        
        // split the list
        $chunks = array_chunk($list, ceil(count($list) / 2));
        $mid = array_pop($chunks[0]);
        
        $node = new Node($mid['key'], $mid['data']);
        $this->insert($node);
        
        $this->_balance($chunks[0]);
        if (isset($chunks[1]))
            $this->_balance($chunks[1]);
    }
    
    /**
     * Balance a binary search tree 
     */
    public function balance()
    {
        $list = array();
        // make a list out of the tree
        $list = $this->_leftRootRight($this->_root);
        
        // find the medium! Because the list is ordered
        // we can find the middle element in various ways
        $chunks = array_chunk($list, ceil(count($list) / 2));
        $mid = array_pop($chunks[0]);
        
        // empty the tree
        $this->_root = null;
        
        // inser the root
        $node = new Node($mid['key'], $mid['data']);
        $this->insert($node);
        
        $this->_balance($chunks[0]);
        $this->_balance($chunks[1]);
    }
	
    /**
     * Insert a new item into the tree
     * 
     * @param type $node 
     */
	public function insert($newNode)
	{
		$this->_insert($newNode, $this->_root);
	}
	
    /**
     * Search by item key
     * 
     * @param int $key
     * @return Node or FALSE
     */
    public function searchByKey($key)
    {
        return $this->_searchByKey($key, $this->_root);
    }
    
    /**
     * @param BalancedBinary $tree
     * @return string 
     */
    protected function _print($tree)
    {
        if ($tree == null) { return ''; }
        
        return $this->_print($tree->getLeft()) . ' ' 
                . $tree->getKey() . ' ' 
                . $this->_print($tree->getRight());
    }
    
    /**
     * Print the tree from left through the root and the right 
     */
    public function __toString()
    {
        if ($this->_root == null) {
            return 'The tree is empty!';
        }

        return $this->_print($this->_root->getLeft()) . ' '
                . $this->_root->getKey() . ' '
                . $this->_print($this->_root->getRight());
    }
}

$a = new Node(90, array(
    'f_name' => 'W.A.',
    'l_name' => 'Mozart',
    'b_day' => '1756-01-27',
));

$b = new Node(100, array(
    'f_name' => 'John',
    'l_name' => 'Smith',
    'b_day' => '23.05.2039',
));

$c = new Node(80, array(
    'f_name' => 'Sarah',
    'l_name' => 'Johnnes',
    'b_day' => 'tomorrow',
));

$d = new Node(60, array(
    'f_name' => 'Ludwig Van',
    'l_name' => 'Beethoven',
    'b_day' => '1770-12-17',
));

$e = new Node(70, array(
    'f_name' => 'Barbara',
    'l_name' => 'Stefanel',
    'b_day' => 'today',
));

$t = new BalancedBinaryTree();

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

echo $t;

echo $t->searchByKey(70);

$t->balance();

echo $t->searchByKey(70);
</pre>
<h2>Complexity of Searching</h2>
<p>Compared to non-balanced binary search trees we’re sure that searching into a balanced trees is quick enough. The maximum height of the tree is <strong>log(n)</strong> so the worst-case searching is <strong>O(log(n))</strong>.</p>
<figure id="attachment_3238" style="width: 600px" class="wp-caption alignnone"><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><figcaption class="wp-caption-text">Compared to searching in linked lists in O(n) time, searching into a balanced binary tree is O(log(n)) in the worst-case scenario!</figcaption></figure>
<h2>Application</h2>
<p>Searching into a balanced binary tree is fast. What is more important is that we&#8217;re sure that in the worst-case scenario the search is O(log(n)). The only problem is that keeping a tree balanced is a slow operation that consumes too much resources and must be performed carefully. </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/06/22/computer-algorithms-binary-search-tree-data-structure/" rel="bookmark" title="Computer Algorithms: Binary Search Tree">Computer Algorithms: 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="/2011/12/26/computer-algorithms-binary-search/" rel="bookmark" title="Computer Algorithms: Binary Search">Computer Algorithms: Binary Search </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/07/03/computer-algorithms-balancing-a-binary-search-tree/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<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>
