Tuesday, 11 October 2016

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
Solution:

 boolean printAncestors(Node node, int target)
    {
         /* base cases */
        if (node == null)
            return false;
  
        if (node.data == target)
            return true;
  
        /* If target is present in either left or right subtree
           of this node, then print this node */
        if (printAncestors(node.left, target)
                || printAncestors(node.right, target))
        {
            System.out.print(node.data + " ");
            return true;
        }
  
        /* Else return false */
        return false;
    }

No comments:

Post a Comment