Sunday, March 5, 2017

Print Ancestors of a given node in Binary Tree

Given a Binary Tree and a key, write a function that prints all the ancestors of the key in the given binary tree.
For example, if the given tree is following Binary Tree and key is 7, then your function should print 4, 2 and 1.
             1
            /   \
          2      3
        /  \
      4     5
     /
    7

Sol:

bool printAncestors(TreeNode T, int target)
{
  if (T == NULL)
     return false;
 
  if (T.data == target)
     return true;
 
  /* If target is present in either left or right sub tree of this node then print this node */
  if ( printAncestors(T.left, target) || printAncestors(T.right, target) )
  {
      System.out.println(T.data + " ");
      return true;
  } 
  return false;
}

Time Complexity: O(n) where n is the number of nodes in the given Binary Tree.

No comments:

Post a Comment