PDA

View Full Version : building tree from a list of nodes


leetleet
03-27-2010, 03:01 AM
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:

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

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. Here's my tree class so far.

//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?

Old Pedant
03-27-2010, 07:14 PM
Of course it always return null.

Look:

if(nodeName.startsWith("end")) return null;

Since the last thing in th input is always an end node, the last thing that happens is always a return null.

You will *never* reach that last line of the recursive function, at any depth.

Rethink the recursive function.

Old Pedant
03-27-2010, 07:18 PM
N.B.: if it's not obvious, this is preparing you to process XML input streams.

Compare

nodeA <nodeA>
nodeB <nodeB>
nodeC <nodeC>
endnodeC </nodeC>
nodeD </nodeB>
endnodeD <nodeD>
endnodeB </nodeD>
endnodeA </nodeA>