Iterative method to find ancestors of a given binary tree

4

Given a binary tree, print all the ancestors of a particular key existing in the tree without using recursion.

Here we will be discussing the c++ implementation for the above problem.
Examples:

Input : 
            1
        /       \
       2         7
     /   \     /   \
    3     5    8    9 
   /       \       /
  4         6     10 
Key = 6 

Output : 5 2 1
Ancestors of 6 are 5, 2 and 1.

The idea is to use iterative postorder traversal of given binary tree.

// C++ program to print all ancestors of a given key
#include <bits/stdc++.h>
using namespace std;

// Structure for a tree node
struct Node {
    int data;
    struct Node* left, *right;
};

// A utility function to create a new tree node
struct Node* newNode(int data)
{
    struct Node* node = (struct Node*)malloc(sizeof(struct Node));
    node->data = data;
    node->left = node->right = NULL;
    return node;
}

// Iterative Function to print all ancestors of a
// given key
void printAncestors(struct Node* root, int key)
{
    if (root == NULL)
        return;

    // Create a stack to hold ancestors
    stack<struct Node*> st;

    // Traverse the complete tree in postorder way till
    // we find the key
    while (1) {

        // Traverse the left side. While traversing, push
        // the nodes into  the stack so that their right
        // subtrees can be traversed later
        while (root && root->data != key) {
            st.push(root); // push current node
            root = root->left; // move to next node
        }

        // If the node whose ancestors are to be printed
        // is found, then break the while loop.
        if (root && root->data == key)
            break;

        // Check if right sub-tree exists for the node at top
        // If not then pop that node because we don't need
        // this node any more.
        if (st.top()->right == NULL) {
            root = st.top();
            st.pop();

            // If the popped node is right child of top,
            // then remove the top as well. Left child of
            // the top must have processed before.
            while (!st.empty() && st.top()->right == root) {
                root = st.top();
                st.pop();
            }
        }

        // if stack is not empty then simply set the root
        // as right child of top and start traversing right
        // sub-tree.
        root = st.empty() ? NULL : st.top()->right;
    }

    // If stack is not empty, print contents of stack
    // Here assumption is that the key is there in tree
    while (!st.empty()) {
        cout << st.top()->data << " ";
        st.pop();
    }
}

// Driver program to test above functions
int main()
{
    // Let us construct a binary tree
    struct Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(7);
    root->left->left = newNode(3);
    root->left->right = newNode(5);
    root->right->left = newNode(8);
    root->right->right = newNode(9);
    root->left->left->left = newNode(4);
    root->left->right->right = newNode(6);
    root->right->right->left = newNode(10);

    int key = 6;
    printAncestors(root, key);

    return 0;
}

Output:

5 2 1

This article is contributed by Gautam Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



4 Average Difficulty : 4/5.0
Based on 2 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.