Print all ancestors of a node in binary tree

Problem: Given a Binary tree and a node’s value, Write a function to print all the ancestors of the node.

Thinking of solution??Think Recursively.This problem can be easily solved using recursion. We start from the root of the tree and keep going down the tree. When we reach the node with given value we return true.if a node contains the given node in left or right subtree we print it and return true to it’s parent till we reach root.

struct node
{
	int data;
	struct node;
};
bool printAncestors(struct node* root,int value)
{

	if(root==NULL)
		return false;

	if(root->data == value)
	return true;

	if(printAncestors(root->left,value)||printAncestors(root->right,value))
	{
		cout<<root->data<<" ";
		return true;
	}
	return false;
}

One Thought on “Print all ancestors of a node in binary tree

  1. void printAllAncestors(node *n) {
    if (!n)
    return;
    else {
    cout<val<par);
    }
    }

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation