Ancestor of a node in a Binary tree

Given a Binary Tree and a value, 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 5, then your function should print  2 and 1.
1
            /   \
          2      3
        /  \
      4     5
     /
    7

Comments

  1. public boolean print_Ancestors(Node root,int key){
    if(root==null){
    return false;
    }
    boolean retleft = print_Ancestors(root.left, key);
    boolean retright = print_Ancestors(root.right, key);
    if(retleft){
    System.out.println(root.value);
    return retleft;
    }
    if(retright){
    System.out.println(root.value);
    return retright;
    }
    if(root.value == key){
    System.out.println(root.value);
    return true;
    }
    else return false;


    }

    ReplyDelete

Post a Comment

Popular posts from this blog

Circular game survival