Return parent of node in Binary Tree

Posted by user188995 on Stack Overflow See other posts from Stack Overflow or by user188995
Published on 2012-09-09T19:15:31Z Indexed on 2013/11/10 9:54 UTC
Read the original article Hit count: 203

I'm writing a code to return the parent of any node, but I'm getting stuck. I don't want to use any predefined ADTs.

//Assume that nodes are represented by numbers from 1...n where 1=root and even 
//nos.=left child and odd nos=right child.
public int parent(Node node){
    if (node % 2 == 0){
       if (root.left==node)
       return root;
    else
       return parent(root.left);
    }
    //same case for right
}

But this program is not working and giving wrong results. My basic algorithm is that the program starts from the root checks if it is on left or on the right. If it's the child or if the node that was queried else, recurses it with the child.

© Stack Overflow or respective owner

Related posts about java

Related posts about algorithm