简体   繁体   中英

Java - finding a parent of a node in a Binary Tree? (converted from a general tree)

I have a binary tree that was converted from a general tree. Meaning, the left node of any given node is that node's child, and the right node of any given node is that node's sibling.

My question is - how can i write a method that will take a node and find its parent? (by traversing the entire tree i guess)

thanks!

Let see if I understand this correctly

It depends on your implementation of tree. Usually tree do not have any cycles and each node have a reference to a child. But again, this is all how the tree is being implemented.

If you are looking for leaf, you can keep recursing to the child of the node until it reaches the base case where child is equal to null.

findLeaves (Node n) {
  if (n == null)
    return;
  else if (n.left == null AND n.right == null)
    return n; // A child
  else
    findLeaves(n.left);
    findLeaves(n.right);

}

Same thing with root. If the node have reference to parent and we are looking for the root. keep recursing to the parents until the parents is null which means that node is a parent.

findRoot (Node n) {
  if (n == null)
    return;
  else if (n.parent == null)
    return n; // A root
  else
    findRoot(n.parent);

}

I hope that helps

this will help you

private static BinaryNode getParent(AnyType x, BinaryNode<AnyType> t, BinaryNode<AnyType> parent) {
        if (t == null) {
            return null;
        } else {
            if (x.compareTo(t.element) < 0) {
                return getParent(x, t.left, t);
            } else if (x.compareTo(t.element) > 0) {
                return getParent(x, t.right, t);
            } else {
                return parent;
            }
        }
    }

if you have a node class that contains 'value' integer variable. a sudo-code can be written as something like this

Node find_parent(Node currentNode, Node parentNode, int valueOfChildNode) {
     Node finalNode = null;
     if ( currentNode->value == valueOfChildNode ) return parentNode;
     if ( currentNode->left_child) 
          finalNode = find_parent(currentNode->left_child,valueOfChildNode,currentNode);
     if ( !finalNode && currentNode->right_child )
          find_parent(currentNode->right_child,valueOfChildNode,currentNode);
     return finalNode;
}

you can change it according to your requirement. you can call it as in the example given below.

find_parent( binaryTree->root_node, null, 15);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM