<?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>Ternary tree &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/ternary-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: Finding the Lowest Common Ancestor</title>
		<link>/2012/08/24/computer-algorithms-finding-the-lowest-common-ancestor/</link>
		<comments>/2012/08/24/computer-algorithms-finding-the-lowest-common-ancestor/#comments</comments>
		<pubDate>Fri, 24 Aug 2012 12:54:54 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[B-tree]]></category>
		<category><![CDATA[Binary search tree]]></category>
		<category><![CDATA[binary search trees]]></category>
		<category><![CDATA[Binary trees]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[Graph theory]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[Lowest common ancestor]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[proper solution]]></category>
		<category><![CDATA[Rope]]></category>
		<category><![CDATA[Ternary tree]]></category>
		<category><![CDATA[Tree]]></category>
		<category><![CDATA[two algorithms]]></category>

		<guid isPermaLink="false">/?p=3314</guid>
		<description><![CDATA[Introduction Here’s one task related to the tree data structure. Given two nodes, can you find their lowest common ancestor? In a matter of fact this task always has a proper solution, because at least the root node is a common ancestor of all pairs of nodes. However here the task is to find the &#8230; <a href="/2012/08/24/computer-algorithms-finding-the-lowest-common-ancestor/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Finding the Lowest Common Ancestor</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<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="/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="/2012/08/07/computer-algorithms-heap-and-heapsort-data-structure/" rel="bookmark" title="Computer Algorithms: Heap and Heapsort">Computer Algorithms: Heap and Heapsort </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>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Here’s one task related to the tree data structure. Given two nodes, can you find their lowest common ancestor? </p>
<p>In a matter of fact this task always has a proper solution, because at least the root node is a common ancestor of all pairs of nodes. However here the task is to find the lowest one, which can be quite far from the root. </p>
<figure id="attachment_3315" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/1.-Finding-the-Lowest-Common-Ancestor.png"><img src="/wp-content/uploads/2012/08/1.-Finding-the-Lowest-Common-Ancestor.png" alt="Finding the Lowest Common Ancestor" title="Finding the Lowest Common Ancestor" width="620" height="362" class="size-full wp-image-3315" srcset="/wp-content/uploads/2012/08/1.-Finding-the-Lowest-Common-Ancestor.png 620w, /wp-content/uploads/2012/08/1.-Finding-the-Lowest-Common-Ancestor-300x175.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Finding the Lowest Common Ancestor</figcaption></figure>
<p>We don’t care what kind of trees we have. However the solution, as we will see, can be very different depending on the tree type. Indeed finding the lowest common ancestor can have linear complexity for binary search trees, which isn’t true for ordinary trees.<span id="more-3314"></span></p>
<h2>Overview</h2>
<p>Let’s say we have a tree (not binary!) and two nodes from this tree. The task is to find their lowest common ancestor. The thing is that we don’t know much about where they appear to be in the tree. </p>
<p>We can think of this tree as a DOM tree of any single HTML page online. It is not binary or balanced and can’t be sure where these nodes are. </p>
<figure id="attachment_3317" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/2.-Lowest-Common-Ancestor.png"><img src="/wp-content/uploads/2012/08/2.-Lowest-Common-Ancestor.png" alt="Lowest Common Ancestor" title="Lowest Common Ancestor" width="620" height="399" class="size-full wp-image-3317" srcset="/wp-content/uploads/2012/08/2.-Lowest-Common-Ancestor.png 620w, /wp-content/uploads/2012/08/2.-Lowest-Common-Ancestor-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>First we must find both paths from the root to each one of the target nodes. Note that this requires additional memory! Then, in linear time we can pass through these “paths” and scan them from the root down to the nodes. We expect these to arrays to be equal at least in their first element (the root).  Using this scenario the lowest common ancestor is the last equal element in both arrays. </p>
<figure id="attachment_3318" style="width: 621px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/3.-Lowest-Common-Ancestor.png"><img src="/wp-content/uploads/2012/08/3.-Lowest-Common-Ancestor.png" alt="Lowest Common Ancestor Paths" title="Lowest Common Ancestor Paths" width="621" height="338" class="size-full wp-image-3318" srcset="/wp-content/uploads/2012/08/3.-Lowest-Common-Ancestor.png 621w, /wp-content/uploads/2012/08/3.-Lowest-Common-Ancestor-300x163.png 300w" sizes="(max-width: 621px) 100vw, 621px" /></a><figcaption class="wp-caption-text">Once we know the paths from the root down to the nodes, we can compare them in order to find the lowest common ancestor!</figcaption></figure>
<p>To see how this algorithm can be dramatically changed depending on the data structure, let’s see another example. Now let’s say we have a binary search tree (BST). We know that in a BST all the elements in the left sub-tree are smaller than the root and all the items on the right sub-tree are greater than the root. This is true also for the left and the right sub-trees.</p>
<p>Now because we’re searching the lowest common ancestor, we don’t need to collect the paths from the root to the nodes in two arrays. We just know that the greater items are on the right, while the smaller items are on the left. This can help us find the lowest ancestor starting directly from the root.</p>
<figure id="attachment_3319" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/08/4.-Lowest-Common-in-a-BST.png"><img src="/wp-content/uploads/2012/08/4.-Lowest-Common-in-a-BST.png" alt="Lowest Common in a BST" title="Lowest Common in a BST" width="620" height="399" class="size-full wp-image-3319" srcset="/wp-content/uploads/2012/08/4.-Lowest-Common-in-a-BST.png 620w, /wp-content/uploads/2012/08/4.-Lowest-Common-in-a-BST-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">In a BST we compare both values with a given node (starting from the root). In case the node&#8217;s value is in between them &#8211; this is the lowest common ancestor. If not &#8211; we go either on the left or on the right!</figcaption></figure>
<p>What we do is to compare the two keys of the target nodes with the root key. If one of the keys are smaller, and the other is greater than the root&#8217;s key, then obviously the root is the lowest common ancestor. This is true because one of the items will be somewhere in the left sub-tree, while the other will be in the right sub-tree. </p>
<p>In case both values are greater (or smaller) than the root, we can move to the right (or to the left) sub-tree and try again with the same procedure. Thus the first node which key is in between the two target values will be the lowest common ancestor.</p>
<h2>Code</h2>
<p>Here’s a very simple PHP implementation showing us these two algorithms.</p>
<pre lang="PHP">
class Tree
{
    public $node = null;
    public $id = null;
    public $parent = null;
    public $children = array();
    
    public function __construct($node, $id = null)
    {
        $this->node = $node;
        $this->id = $id;
    }
    
    public function addChild(Node &$n)
    {
        $n->parent = $this;
        $this->children[] = $n;
    }
    
    /**
     * Returns an element by its id
     * 
     * @param mixed $id
     * @return Node 
     */
    public function search($id)
    {
        if ($this->id == $id) {
            return $this;
        }

        $a = false;
        
        // search all the children starting from the left-most
        foreach ($this->children as $child) {
            $a = $child->search($id);
        }
        
        return $a;
    }
    
    /**
     * Finds a path from the root to the 
     * item and returns it as a list
     * 
     * @param mixed $id 
     * @return array
     */
    public function find_path($id, &$path)
    {
        array_push($path, $this->id);
        
        if ($this->id == $id) {
            return 1;
        }
        
        foreach ($this->children as $child)  {
            if (1 == $child->find_path($id, $path)) return 1;
            array_pop($path);
        }
    }
    
    public function __toString()
    {
        return $this->node . ' ' . $this->id . "\n";
    }
}

$dom = new Tree('DOM', 'ROOT');

$body = new Tree('BODY', 1);
$div1 = new Tree('DIV', 'div-1');
$div2 = new Tree('DIV', 'my-id');

$a = new Tree("A", 'some-link');

$dom->addChild($body);
$body->addChild($div1);
$body->addChild($div2);
$div2->addChild($a);

$path1 = $path2 = array();
$dom->find_path('div-1', $path1);
$dom->find_path('some-link', $path2);
</pre>
<h3>Finding Lowest Common Ancestor in a BST</h3>
<pre lang="PHP">
class Tree
{
    public $key;
    
    public $parent  = null;
    public $left    = null;
    public $right   = null;
    
    public function __construct($key) 
    {
        $this->key = $key;
    }
    
    public function insert(Tree $n) 
    {
        if ($this->key < $n->key) {
            if ($this->right == null) {
                // insert
                $this->right = $n;
                $n->parent = $this;
            } else {
                $this->right->insert($n);
            }
        }
        if ($this->key > $n->key) {
            if ($this->left == null) {
                // insert
                $this->left = $n;
                $n->parent = $this;
            } else {
                $this->left->insert($n);
            }
        }
    }
}

$t = new Tree(10);

$n1 = new Tree(20);
$n2 = new Tree(5);
$n3 = new Tree(7);
$n4 = new Tree(13);

$t->insert($n1);
$t->insert($n2);
$t->insert($n3);

function find_common($node1, $node2, $tree) 
{
    if ($node1->key < $tree->key && $node2->key > $tree->key) {
        return $tree;
    } else if ($node1->key < $tree->key && $node2->key < $tree->key) {
        find_common($node1, $node2, $tree->left);
    } else if ($node1->key > $tree->key && $node2->key > $tree->key) {
        find_common($node1, $node2, $tree->right);
    }
}

$node = find_common($n3, $n4, $t);
</pre>
<h2>Application</h2>
<p>A typical use-case of this algorithm is finding the lowest common ancestor of two nodes in a DOM tree. Sometimes we just need to attach an event listener to both items (even before they are attached to the DOM!). Although attaching this event to the “document” will work just fine, all the elements from the nodes up to the root will be “capturing” these events due to event bubbling. Thus attaching the event to the lowest common ancestor is a better solution.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<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="/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="/2012/08/07/computer-algorithms-heap-and-heapsort-data-structure/" rel="bookmark" title="Computer Algorithms: Heap and Heapsort">Computer Algorithms: Heap and Heapsort </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>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/08/24/computer-algorithms-finding-the-lowest-common-ancestor/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
