building tree from a list of nodes

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • neetlife
    New Member
    • Mar 2010
    • 1

    building tree from a list of nodes

    Hi. There's this tree I need to build, and I'm having problems with it.

    I have to read the nodes from a file, which are sorted inorder, and have marker nodes to show where branches end. For example, I have two text files here, with what the trees should look like under them.
    Code:
    nodeA          nodeA
    nodeB          nodeB
    nodeC          nodeC
    endnodeC       endnodeC
    nodeD          endnodeB
    endnodeD       nodeD
    endnodeB       endnodeD
    endnodeA       endnodeA
        A              A
        |             / \
        B            B   D
       / \           |
      C   D          C
    My node class is simply
    Code:
    public class node {
        String s;
        ArrayList<node> children;
        public node(String s) {
            this.s = s;
            children = null;
        }
        //other functions
    }
    As for the tree, I'm having trouble building it.
    I read the nodes from the txt file into an ArrayList of nodes. Here's my tree class so far.
    Code:
    //n is the list of nodes read from file
    public tree(ArrayList<node> n) {
        //make tree
        root = buildTree(n);
    }
    
    //return root of new tree
    public node buildTree(ArrayList<node> n) {
        node newNode = null;
        while(!n.isEmpty()) {
            String nodeName = n.get(0).toString();
    
            //check if marker node
            if(nodeName.startsWith("end")) return null;
    
            newNode = new node(nodeName);
            n.remove(0);
    
            //recurse
            newNode.addChild(buildTree(n));
        }
        return newNode;
    }
    However, when I run it, root is still null.
    I'm wondering if this is even the correct way to go about building this tree. Any advice?
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    Here's the mistake:
    if(nodeName.sta rtsWith("end")) return null;
    The first endnode will cascade null down the entire tree.

    You want:
    if(nodeName.sta rtsWith("end")) {
    n.remove(0);
    return null;
    }

    Comment

    Working...