I'm trying to traverse a tree using ANTLR tree commands and recursion. The code I currently have is:
public void traverseTree(Tree tree){
int counter = 0;
System.out.println(tree.toString());
if (tree.getChildCount() > 0 && tree.getChild(0) != null){
System.out.println(tree.toString() + counter++);
tree = tree.getChild(0);
traverseTree(tree);
}
while (tree.getParent().getChild(tree.getChildIndex() + 1) != null){
System.out.println(tree.toString() + counter++);
tree = tree.getParent().getChild(tree.getChildIndex() + 1);
traverseTree(tree);
}
}
But, well, it's not working. I'm getting a lot of the entries in the tree, but in no obvious order. Can anyone see where I'm going wrong?
Thanks.
EDIT:
Comment I made below that should have been here to begin with:
Sorry, I should have removed the print statements, they were just there to try and debug it. The problem I'm encountering is that it should only search the node it starts on and any siblings of that node, it shouldn't go up a level, but it does, it prints everything. (I'll edit this into the main, it should have been there to begin with, sorry).
I managed to get the code working eventually like so:
public void traverseTree(Tree tree){
System.out.println(tree);
if (tree.getChild(0) != null){
traverseTree(tree.getChild(0));
}
if(tree.getParent().getChildCount() > 1){
if(tree.getParent().getChild(tree.getChildIndex() + 1) != null)
traverseTree(tree.getParent().getChild(tree.getChildIndex() + 1));
}
}