{"id":3549,"date":"2018-01-14T13:50:00","date_gmt":"2018-01-14T08:20:00","guid":{"rendered":"http:\/\/theoryofprogramming.azurewebsites.net\/?p=3549"},"modified":"2018-01-14T13:50:00","modified_gmt":"2018-01-14T08:20:00","slug":"n-ary-tree-k-way-tree-data-structure","status":"publish","type":"post","link":"https:\/\/theoryofcoding.com\/index.php\/2018\/01\/14\/n-ary-tree-k-way-tree-data-structure\/","title":{"rendered":"N-ary tree or K-way tree data structure"},"content":{"rendered":"<p>Hello people! In this post, we will talk about a generic tree data structure which is N-ary tree or also known as k-way tree. N-ary tree is defined as a rooted tree which has at most N children for any node. So, a binary tree is a special case of the N-ary tree, where N = 2. Example &#8211;<\/p>\n<p><a href=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2018\/01\/n-ary-tree-1.jpg?ssl=1\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-3551\" src=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2018\/01\/n-ary-tree-1.jpg?resize=575%2C518&#038;ssl=1\" alt=\"N-ary tree Theory of Programming\" width=\"575\" height=\"518\" srcset=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2018\/01\/n-ary-tree-1.jpg?w=575&amp;ssl=1 575w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2018\/01\/n-ary-tree-1.jpg?resize=300%2C270&amp;ssl=1 300w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2018\/01\/n-ary-tree-1.jpg?resize=230%2C207&amp;ssl=1 230w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2018\/01\/n-ary-tree-1.jpg?resize=350%2C315&amp;ssl=1 350w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2018\/01\/n-ary-tree-1.jpg?resize=480%2C432&amp;ssl=1 480w\" sizes=\"auto, (max-width: 575px) 100vw, 575px\" data-recalc-dims=\"1\" \/><\/a>The above example is a N-ary tree with N = 3. You can observe that each node has no more than 3 children.<\/p>\n<p>In many scenarios, having a binary tree many not be enough as a situation can often lead to more than 2 situations. In such cases, we must form a N-ary tree of sufficiently large N.<\/p>\n<h2>Implementing N-ary tree using structures<\/h2>\n<p>Implementing N-ary tree is very simple. It is even more easy if you already know how to implement a <a href=\"http:\/\/theoryofprogramming.azurewebsites.net\/2015\/01\/16\/trie-tree-implementation\/\">Trie Tree<\/a>. Now, in the case of binary tree, the node structure was like this &#8211;<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nclass TreeNode {\n    String label;\n    Node leftChild, rightChild;\n}\n<\/pre>\n<p>Having two references was enough for us then because we knew we would have at most 2 children. Now, we can have at most N children. How will you store a collection of N references? By using an array! In the case of Java, I&#8217;d like to use an <em>ArrayList<\/em> rather than an array. In the case of C++, I&#8217;d suggest you go for a C++ STL <em>vector<\/em>. So now our node structure will look like this &#8211;<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nclass NaryTreeNode {\n    String label;\n    ArrayList&lt;NaryTreeNode&gt; children;\n    int n;\n}\n<\/pre>\n<p>Storing the value of N inside the node will enable us to put a restriction on the number of children. So we will add methods inside our newly formed <em>NaryTreeNode<\/em> class to manipulate the member variables. Some important methods would be &#8211;<\/p>\n<ul>\n<li><span style=\"font-family: Consolas;\">addChild(child)<\/span> &#8211; to add a child node.<\/li>\n<li><span style=\"font-family: Consolas;\">getChildren()<\/span> &#8211; to get all the child nodes.<\/li>\n<li><span style=\"font-family: Consolas;\">getChild(index)<\/span> &#8211; to get child at a certain index.<\/li>\n<li><span style=\"font-family: Consolas;\">print(root)<\/span> &#8211; to print the tree. (This can be a static method, where we just supply the root node).<\/li>\n<\/ul>\n<p>Also, don&#8217;t forget to add a constructor to your class! Now you are all set to write the code for N-ary tree. Try to code it, this is something you should be able to code in 1-3 attempts. You can refer to my code below if you get stuck &#8211;<\/p>\n<div class=\"su-tabs su-tabs-style-default su-tabs-mobile-stack\" data-active=\"1\" data-scroll-offset=\"0\" data-anchor-in-url=\"no\"><div class=\"su-tabs-nav\"><span class=\"\" data-url=\"\" data-target=\"blank\" tabindex=\"0\" role=\"button\">Java<\/span><span class=\"\" data-url=\"\" data-target=\"blank\" tabindex=\"0\" role=\"button\">Output<\/span><\/div><div class=\"su-tabs-panes\"><div class=\"su-tabs-pane su-u-clearfix su-u-trim\" data-title=\"Java\">\n<strong>Link to code &#8211; <a href=\"https:\/\/github.com\/VamsiSangam\/theoryofprogramming\/blob\/master\/Tree%20Data%20Structures\/N-ary%20Tree\/Java\/NaryTreeNode.java\">GitHub<\/a><\/strong><br \/>\n<\/div>\n<div class=\"su-tabs-pane su-u-clearfix su-u-trim\" data-title=\"Output\">\n[code]\nMatter<br \/>\n   Pure<br \/>\n      Elements<br \/>\n         Metals<br \/>\n         Metalloids<br \/>\n         Non-metals<br \/>\n      Compounds<br \/>\n         Water<br \/>\n         Carbon dioxide<br \/>\n         Salt<br \/>\n   Mixture<br \/>\n      Homogeneous<br \/>\n         Air<br \/>\n         Vinegar<br \/>\n      Heterogeneous<br \/>\n         Colloids<br \/>\n         Suspensions<br \/>\n[\/code]\n<\/div><\/div><\/div>\n<p>I have added a helper method for printing the tree so that the tree can be printed more legibly based on the depth of nodes. I have also modified the <em>addChild()<\/em> method a little. It only accepts the new child&#8217;s label as it&#8217;s <em>N<\/em> value can be deduced from the parent node. The code should be easy to understand. Do leave a comment if you have any doubts \ud83d\ude42<\/p>\n<h2>Implementing N-ary tree using arrays<\/h2>\n<p>Remember you can implement a binary tree using arrays. Similarly, you can also implement an N-ary tree using arrays. It is very similar to how you would do it in the case of binary trees, so here the formula for computing child node and parent node changes.<\/p>\n<div class=\"su-table su-table-alternate\">\n<table>\n<tbody>\n<tr>\n<td><\/td>\n<td>Parent node<\/td>\n<td>Child node<\/td>\n<\/tr>\n<tr>\n<td>Binary tree<\/td>\n<td>\n<a href=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2018\/01\/binary-parent.png?ssl=1\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-3559\" src=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2018\/01\/binary-parent.png?resize=73%2C60&#038;ssl=1\" alt=\"Parent node in binary tree\" width=\"73\" height=\"60\" data-recalc-dims=\"1\" \/><\/a><\/td>\n<td>Left child &#8211;<br \/>\n<a href=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2018\/01\/binary-left-child.png?ssl=1\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-3558\" src=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2018\/01\/binary-left-child.png?resize=108%2C25&#038;ssl=1\" alt=\"Left child in binary tree\" width=\"108\" height=\"25\" data-recalc-dims=\"1\" \/><\/a><br \/>\nRight Child &#8211;<br \/>\n<a href=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2018\/01\/binary-right-child.png?ssl=1\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-3560\" src=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2018\/01\/binary-right-child.png?resize=108%2C25&#038;ssl=1\" alt=\"Right child in binary tree\" width=\"108\" height=\"25\" data-recalc-dims=\"1\" \/><\/a><\/td>\n<\/tr>\n<tr>\n<td>N-ary Tree<\/td>\n<td><a href=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2018\/01\/n-ary-parent.png?ssl=1\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-3561\" src=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2018\/01\/n-ary-parent.png?resize=73%2C60&#038;ssl=1\" alt=\"Parent node in N-ary tree\" width=\"73\" height=\"60\" data-recalc-dims=\"1\" \/><\/a><\/td>\n<td>C<sup>th<\/sup> child &#8211;<br \/>\n<a href=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2018\/01\/n-ary-child.png?ssl=1\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-3557\" src=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2018\/01\/n-ary-child.png?resize=110%2C25&#038;ssl=1\" alt=\"Child in an N-ary tree\" width=\"110\" height=\"25\" data-recalc-dims=\"1\" \/><\/a><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p>Using the above table, you can find the parent and child node for a node at index <em>i<\/em>. Generally, I like to implement the tree using structures, but if you have a complete n-ary tree, then the array representation will you a better compact storage.<\/p>\n<p>I hope this article was able to give you an idea of how to implement an N-ary tree. Keep practicing! Happy coding! \ud83d\ude00<\/p>\n","protected":false},"excerpt":{"rendered":"<p>N-ary tree is defined as a rooted tree which has at most N children for any node. So, a binary tree is a special case of the N-ary tree, where N = 2. We ca implement an N-ary tree using structures or using arrays.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[14],"tags":[70,82,111],"class_list":["post-3549","post","type-post","status-publish","format-standard","hentry","category-tree-data-structures","tag-k-way-tree","tag-n-ary-tree","tag-trees"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/posts\/3549","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/comments?post=3549"}],"version-history":[{"count":0,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/posts\/3549\/revisions"}],"wp:attachment":[{"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/media?parent=3549"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/categories?post=3549"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/tags?post=3549"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}