user98456
user98456

Reputation: 137

backtrace a tree without mutable members

I am trying to make a recursive tree such that parent has reference to child and child has reference to parent. The thing I am trying to do is to backtrace the tree from a child whitout mutable members. It is hard because giving the child a reference to the parent in the constructor requireds the parent instance to be already created.

I only could think of two ways and both are not so good. The first way is the fallowing

  1. create child instance with function "setParent()" which only works once with the help of a private boolean variable.
  2. create parent and pass the child instance.
  3. the parent will pass itself to "setParent()".

After that, child has reference to parent and setParent() cannot be used.

The second way is to create parent and child completly separate but hold them in some sort of data structure which can search for parent of some child and the otherway arround.

If there is a better way please teach me. I work mainly in java but the question is general.

Upvotes: 0

Views: 104

Answers (1)

Henry Keiter
Henry Keiter

Reputation: 17168

There are several ways to do this, but I'd probably give the parent a createChild method that creates a new node, passing itself as the parent, and adds this child to itself before returning it. You imply in the question that having a preexisting parent is difficult for some reason, but if you're making a tree, you ought to know whose parents are whose. If you don't, a tree might not be the data structure you're looking for.

I'd probably structure it such that your Element constructor may take another Element. If so, it sets a private variable (parent) to that other Element. If it's created without a parent element passed in, it will never have a parent. So the class might look something like this (omitting accessors and any other stuff obviously):

public class Element {

    private Element parent;
    private ArrayList<Element> children;

    // Constructor for a node with NO parent
    public Element() {
        this(null);
    }

    // Constructor for a node WITH a parent
    public Element(Element parent) {
        this.parent = parent;
        this.children = new ArrayList<Element>();
    }

    // Method to create a child element.
    public Element createChild() {
        Element ch = new Element(this);
        this.children.add(ch);
        return ch;
    }
}

If your problem is that you're trying to build a "tree" by tracing from a child up to some ancestor, then I encourage you to notice that that's actually a list, not a tree. You can just make the list from bottom to top and then build the tree from top to bottom by starting at the end of the list.

Upvotes: 1

Related Questions