First of all, I´m aware of having to create a new Tree instance in every iteration as not to reuse the same object and also having static objects as this and this threads inform.I think I´ve checked every part of the code for that.
So, I am testing the code below. A bit of information on what it does:
The first loop iterates over a List of Root nodes with children forming a binary tree. I create a tree object for every root node and add it to it, the object also contains two arraylist one for all nodes in the tree and another for just the leaves. In the loop I also set numbers randomly to every leaf in every tree from 1 to n (where n is the number of leafs in the tree) and add the tree to an arrayList : possibleTrees.
Problem: In the first loop when I iterate over the leaves of every tree and print their numbers it prints them accordingly. But after it finishes and I iterate over possibleTrees printing all tree´s leaves, many values change.
Here´s the code and the output below it for a tree with 4 leaves. The top part prints twice because one is an arraylist of integers and the second one is printing the values directly from the nodes
Edit: Link to Tree,Node classes
Edit2 : added alltopologies class (http://) pastebin.com/sB9UV8T6
ArrayList<Tree> possibleTrees = new ArrayList<Tree>();
ArrayList<Integer> numbers = new ArrayList<Integer>();
for (int i = 0; i < numNodes; i++) {
numbers.add(i + 1);
}
for (Node n : allTopologies.allBinaryTrees(numNodes)) {
Tree tree = new Tree();
tree.setNodesLists(n);
Collections.shuffle(numbers);
tree.setleafNums(n, numbers);
tree.setRoot(n);
possibleTrees.add(tree);
System.out.println(numbers);
System.out.print("[");
for (Node l : tree.getLeaves()) {
System.out.print(l.getLeafNum() + ", ");
}
System.out.println("]");
System.out.println("");
}
System.out.println("-------------------------------");
for (Tree t : possibleTrees) {
System.out.print("[");
for (Node l : t.getLeaves()) {
System.out.print(l.getLeafNum() + ", ");
}
System.out.println("]");
System.out.println("");
}
OutPut:
[3, 2, 1, 4]
[3, 2, 1, 4, ]
[2, 4, 1, 3] [2, 4, 1, 3, ]
[2, 4, 1, 3] [2, 4, 1, 3, ]
[1, 3, 2, 4] [1, 3, 2, 4, ]
[3, 4, 2, 1] [3, 4, 2, 1, ]
[2, 2, 1, 4, ]
[2, 4, 1, 3, ]
[2, 4, 1, 3, ]
[1, 3, 2, 1, ]
[3, 4, 2, 1, ]
Thanks in advance !