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.
My node class is simply
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.
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?
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
Code:
public class node {
String s;
ArrayList<node> children;
public node(String s) {
this.s = s;
children = null;
}
//other functions
}
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;
}
I'm wondering if this is even the correct way to go about building this tree. Any advice?
Comment