Given a Binary tree and an integer, print all the ancestors of the node. For example: If the given tree is as below:

Input: 5      Output: 10
Input: 40     Output: 30 10
Input: 1      Output: 4 5 10

Solution:

If Node of the binary tree is defined as below:

    struct Node
    {
        int data;
        Node *left;
        Node *right;
    };

Algorithm:

To print the ancestors, the logic is as below:

At any point true means the node is an ancestor of the given node. A false means that the given node is neither in the left nor in the right-sub-tree of this node, hence this node is not the ancestor.

Code:

    bool printAncestors(Node *r, int d)
    {
        if(r == NULL)
            return false;
        if(r->data == d )
            return true;
        if( printAncestors(root->left, d) || printAncestors(root->right, d) )
        {
            cout << root->data << " ";
            return true;
        }
        else
        {
            return false;
        }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *