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.
Expand|Select|Wrap|Line Numbers
- nodeA nodeA
- nodeB nodeB
- nodeC nodeC
- endnodeC endnodeC
- nodeD endnodeB
- endnodeD nodeD
- endnodeB endnodeD
- endnodeA endnodeA
- A A
- | / \
- B B D
- / \ |
- C D C
Expand|Select|Wrap|Line Numbers
- 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.
Expand|Select|Wrap|Line Numbers
- //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?