tags:

views:

276

answers:

2

Related to my question about how to build a tree-like structure, the data I receive from the server are in arrays like this: {School Chair Table Chalk}

How can I loop through this so that:

  • School becomes parent of Chair
  • Chair becomes parent of Table
  • Table becomes parent of Chalk
+1  A: 

Assuming a Node class that offers a constructor which accepts the node's value as an argument and method addChild that adds another Node as a child and sets itself as the child's parent, the code could look like this:

Node currentNode = null;
for(String value: array) {
    Node node = new Node(value);
    if(currentNode != null) {
        currentNode.addChild(node);
    }
    currentNode = node;
}
sepp2k
I should add that this does not keep track of the root node. That might not be a problem, depending on how the node class is designed and used. If you do need to keep track of the root however, you can easily add something like else { rootNode = node; } to the above code.Alternatively you might handle the first item of the array before the loop.
sepp2k
+1  A: 

Are they always in a list that becomes hierarchical in order? I would suggest creating a simple wrapper class...pardon my syntax, as I've been playing in C# for a while now:

public class Node {
    public string description;
    public Node child;

    public Node(List<string> descriptions) {

        this.description = descriptions.RemoveAt(0);
        if (descriptions.Count > 0) {
            this.child = new Node(descriptions);  //create child node with remaining items
        }
    }
}

This will take issue if you pass in a list w/ zero items to the constructor, but that's easily remedied.

jkelley