I am new at java and i fight my way through... I have to do some homework and i resolve a lot from it, but at some points i dont know how to do it. My Problem: I must build some functions for a binary Tree (such as add nodes, count nodes, delete nodes, etc). Most of them i could find myself the algorithm. Now i struggle with a recursive method. I put commentaries into it to explain what my problem is:
public List<E> getPreOrderList() {
//TO DO:
//this function should return a list of the nodes in pre-order (value, left, right).
//It must be implemented recursively!!!
//THE PROBLEM:
//If i create an ArrayList<E> inside the function, the
//recursion will generate each time a new ArrayList.
//At the end i get as result an ArrayList with only one node.
ArrayList<E> list = new ArrayList<E>();
if (this.value == null) {
return null;
}
//If I just print out the nodes, the pre-order algorithm is OK,
//but i need to return all nodes into an ArrayList.
System.out.print(value + ", ");
list.add(value);
if (left != null) {
left.getPreOrderList();
}
if (right != null) {
right.getPreOrderList();
}
return list;
}