¿Agregar padres a los nodos en el árbol?

I have a tree structure and I want to be able to go through and add the parent node to a data parent variable that each child node has.

The structure of the tree is:

Class Tree {
     Node root;
}

Class Node {
     String data;
     Node parent;
     List<Node> children;
}

¿alguna sugerencia?

EDIT to be more specific

 public void addParent() {
    for (Node child : curNode.children) {
        child.parent = curNode;
        curNode = child;
        findDFS(value);
    }
    return null;
}

with that code and the given tree:

     A
    /  \
   D    E
       / \
       B  S

E's parent is D when it should be A, why is that?

preguntado el 27 de noviembre de 13 a las 01:11

As it currently stands, this question is very vague. Consider posting some examples of what you have tried and what problems you are facing. -

I made it more specific -

You mean E's parent is A? Also, can the parent only have 2 child or more than 2 child since you made a list for children? -

By "specific", I think Daemon also meant more along the lines of: what is it that you're asking? Are you encountering an error? What is the expected behaviour, and what is the observed or actual behaviour? -

I meant it E's parent is getting set to D when it should be A. -

1 Respuestas

E's parent is D when it should be A, why is that?

In your loop you're doing:

for (Node child : curNode.children) {
    child.parent = curNode;
    curNode = child; // <-- problem is here!!!
    findDFS(value);
}

which means: in the first loop you're assigning the child to the current node and continue looping over the next child with the first child as a "parent" and then again...

Respondido el 08 de diciembre de 14 a las 03:12

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.