I've managed to set up a binary tree and can print the contents as it inserts the nodes. However, when I use a method to traverse the tree, I can create a traversal, producing multiple single arrayLists, but when I try to populate a single arrayList with the traversal I get a NullPointerException and I'm not sure why.
The original that works.
@Override
public List<T> traverse() {
List<T> traversal = new ArrayList<T>();
populateTraversalList(this,traversal);
if (this.isEmpty()) {
return null;
} else {
traversal.add(this.getValue());
root.getLeft().traverse();
root.getRight().traverse();
}
System.out.println(traversal.toString());
return traversal;
}
Produces the output. When given an Integer binary tree produced from an array of {0, 1, 2, 4 , 3, 5, 6, 7}.
[3]
[7]
[6]
[5]
[4]
[2]
[1]
[0]
But when I try to neaten it up it gets nullptrs.
@Override
public List<T> traverse() {
List<T> traversal = new ArrayList<T>();
populateTraversalList(this,traversal);
System.out.println(traversal.toString());
return traversal;
}
private void populateTraversalList(BinaryTree<T> searchTree, List<T> traversalList) {
if (this.isEmpty()) {
return;
} else {
traversalList.add(getValue());
populateTraversalList((BinaryTree<T>) searchTree.getLeft(), traversalList);
populateTraversalList((BinaryTree<T>) searchTree.getRight(), traversalList);
}
}
It seems to specifically object to the searchTree.getLeft() line, but from my understanding I should be passing on the same instance into the first parameter. Thank you in advance.