{"id":27552,"date":"2018-02-06T20:56:55","date_gmt":"2018-02-06T15:26:55","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27552"},"modified":"2018-02-06T20:56:55","modified_gmt":"2018-02-06T15:26:55","slug":"print-ancestors-given-binary-tree-node-without-recursion","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/print-ancestors-given-binary-tree-node-without-recursion\/","title":{"rendered":"Print ancestors of a given binary tree node without recursion"},"content":{"rendered":"<p>Given a Binary Tree and a key, write a function that prints all the ancestors of the key in the given binary tree.<span id=\"more-119933\"><\/span><\/p>\n<p>For example, consider the following Binary Tree<\/p>\n<pre>            1\r\n        \/       \\\r\n       2         3\r\n     \/   \\     \/   \\\r\n    4     5    6    7 \r\n   \/       \\       \/\r\n  8         9     10<\/pre>\n<p>Following are different input keys and their ancestors in the above tree<\/p>\n<pre>Input Key    List of Ancestors \r\n-------------------------\r\n 1            \r\n 2            1\r\n 3            1\r\n 4            2 1\r\n 5            2 1\r\n 6            3 1\r\n 7            3 1\r\n 8            4 2 1\r\n 9            5 2 1\r\n10            7 3 1\r\n<\/pre>\n<p>Recursive solution for this problem is discussed here.<br \/>\nIt is clear that we need to use a stack based iterative traversal of the Binary Tree. The idea is to have all ancestors in stack when we reach the node with given key. Once we reach the key, all we have to do is, print contents of stack.<br \/>\nHow to get all ancestors in stack when we reach the given node? We can traverse all nodes in Postorder way. If we take a closer look at the recursive postorder traversal, we can easily observe that, when recursive function is called for a node, the recursion call stack contains ancestors of the node. So idea is do iterative Postorder traversal and stop the traversal when we reach the desired node.<\/p>\n<p>Following is C implementation of the above approach.<\/p>\n<p><strong>C Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/\/ C program to print all ancestors of a given key<br\/>#include &lt;stdio.h&gt;<br\/>#include &lt;stdlib.h&gt;<br\/> <br\/>\/\/ Maximum stack size<br\/>#define MAX_SIZE 100<br\/> <br\/>\/\/ Structure for a tree node<br\/>struct Node<br\/>{<br\/>    int data;<br\/>    struct Node *left, *right;<br\/>};<br\/> <br\/>\/\/ Structure for Stack<br\/>struct Stack<br\/>{<br\/>    int size;<br\/>    int top;<br\/>    struct Node* *array;<br\/>};<br\/> <br\/>\/\/ A utility function to create a new tree node<br\/>struct Node* newNode(int data)<br\/>{<br\/>    struct Node* node = (struct Node*) malloc(sizeof(struct Node));<br\/>    node-&gt;data = data;<br\/>    node-&gt;left = node-&gt;right = NULL;<br\/>    return node;<br\/>}<br\/> <br\/>\/\/ A utility function to create a stack of given size<br\/>struct Stack* createStack(int size)<br\/>{<br\/>    struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));<br\/>    stack-&gt;size = size;<br\/>    stack-&gt;top = -1;<br\/>    stack-&gt;array = (struct Node**) malloc(stack-&gt;size * sizeof(struct Node*));<br\/>    return stack;<br\/>}<br\/> <br\/>\/\/ BASIC OPERATIONS OF STACK<br\/>int isFull(struct Stack* stack)<br\/>{<br\/>    return ((stack-&gt;top + 1) == stack-&gt;size);<br\/>}<br\/>int isEmpty(struct Stack* stack)<br\/>{<br\/>    return stack-&gt;top == -1;<br\/>}<br\/>void push(struct Stack* stack, struct Node* node)<br\/>{<br\/>    if (isFull(stack))<br\/>        return;<br\/>    stack-&gt;array[++stack-&gt;top] = node;<br\/>}<br\/>struct Node* pop(struct Stack* stack)<br\/>{<br\/>    if (isEmpty(stack))<br\/>        return NULL;<br\/>    return stack-&gt;array[stack-&gt;top--];<br\/>}<br\/>struct Node* peek(struct Stack* stack)<br\/>{<br\/>    if (isEmpty(stack))<br\/>        return NULL;<br\/>    return stack-&gt;array[stack-&gt;top];<br\/>}<br\/> <br\/>\/\/ Iterative Function to print all ancestors of a given key<br\/>void printAncestors(struct Node *root, int key)<br\/>{<br\/>    if (root == NULL) return;<br\/> <br\/>    \/\/ Create a stack to hold ancestors<br\/>    struct Stack* stack = createStack(MAX_SIZE);<br\/> <br\/>    \/\/ Traverse the complete tree in postorder way till we find the key<br\/>    while (1)<br\/>    {<br\/>        \/\/ Traverse the left side. While traversing, push the nodes into<br\/>        \/\/ the stack so that their right subtrees can be traversed later<br\/>        while (root &amp;&amp; root-&gt;data != key)<br\/>        {<br\/>            push(stack, root);   \/\/ push current node<br\/>            root = root-&gt;left;  \/\/ move to next node<br\/>        }<br\/> <br\/>        \/\/ If the node whose ancestors are to be printed is found,<br\/>        \/\/ then break the while loop.<br\/>        if (root &amp;&amp; root-&gt;data == key)<br\/>            break;<br\/> <br\/>        \/\/ Check if right sub-tree exists for the node at top<br\/>        \/\/ If not then pop that node because we don&#039;t need this<br\/>        \/\/ node any more.<br\/>        if (peek(stack)-&gt;right == NULL)<br\/>        {<br\/>            root = pop(stack);<br\/> <br\/>            \/\/ If the popped node is right child of top, then remove the top<br\/>            \/\/ as well. Left child of the top must have processed before.<br\/>            \/\/ Consider the following tree for example and key = 3.  If we<br\/>            \/\/ remove the following loop, the program will go in an<br\/>            \/\/ infinite loop after reaching 5.<br\/>            \/\/          1<br\/>            \/\/        \/   \\<br\/>            \/\/       2     3<br\/>            \/\/         \\<br\/>            \/\/           4<br\/>            \/\/             \\<br\/>            \/\/              5<br\/>            while (!isEmpty(stack) &amp;&amp; peek(stack)-&gt;right == root)<br\/>               root = pop(stack);<br\/>        }<br\/> <br\/>        \/\/ if stack is not empty then simply set the root as right child<br\/>        \/\/ of top and start traversing right sub-tree.<br\/>        root = isEmpty(stack)? NULL: peek(stack)-&gt;right;<br\/>    }<br\/> <br\/>    \/\/ If stack is not empty, print contents of stack<br\/>    \/\/ Here assumption is that the key is there in tree<br\/>    while (!isEmpty(stack))<br\/>        printf(&quot;%d &quot;, pop(stack)-&gt;data);<br\/>}<br\/> <br\/>\/\/ Driver program to test above functions<br\/>int main()<br\/>{<br\/>    \/\/ Let us construct a binary tree<br\/>    struct Node* root = newNode(1);<br\/>    root-&gt;left = newNode(2);<br\/>    root-&gt;right = newNode(3);<br\/>    root-&gt;left-&gt;left = newNode(4);<br\/>    root-&gt;left-&gt;right = newNode(5);<br\/>    root-&gt;right-&gt;left = newNode(6);<br\/>    root-&gt;right-&gt;right = newNode(7);<br\/>    root-&gt;left-&gt;left-&gt;left = newNode(8);<br\/>    root-&gt;left-&gt;right-&gt;right = newNode(9);<br\/>    root-&gt;right-&gt;right-&gt;left = newNode(10);<br\/> <br\/>    printf(&quot;Following are all keys and their ancestors\\n&quot;);<br\/>    for (int key = 1; key &lt;= 10; key++)<br\/>    {<br\/>        printf(&quot;%d: &quot;, key);<br\/>        printAncestors(root, key);<br\/>        printf(&quot;\\n&quot;);<br\/>    }<br\/> <br\/>    getchar();<br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>Following are all keys and their ancestors\r\n1:\r\n2: 1\r\n3: 1\r\n4: 2 1\r\n5: 2 1\r\n6: 3 1\r\n7: 3 1\r\n8: 4 2 1\r\n9: 5 2 1\r\n10: 7 3 1<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Print ancestors of a given binary tree node without recursion &#8211; Stack &#8211; Given a Binary Tree and a key, write a function that prints all the ancestors<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[73012,79607],"tags":[81755,81754,81751,81757,81752,81756,81753,81760,81758,81759],"class_list":["post-27552","post","type-post","status-publish","format-standard","hentry","category-data-structures","category-stack","tag-ancestor-in-tree-data-structure","tag-ancestor-node-definition","tag-ancestors-of-a-node-in-a-binary-tree","tag-check-if-all-leaves-are-at-same-level","tag-common-ancestor-of-two-nodes-in-a-binary-tree","tag-descendant-in-tree-data-structure","tag-find-parent-of-a-node-in-binary-tree","tag-find-parent-of-a-node-in-binary-tree-c","tag-find-parent-of-a-node-in-binary-tree-in-c","tag-print-ancestors-of-a-given-binary-tree-node-without-recursion"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27552","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=27552"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27552\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27552"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27552"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27552"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}