-1

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.

Alistair
  • 19
  • 5
  • Q: Where are you checking that the current value of `searchTree` isn't "null"? – paulsm4 Dec 24 '18 at 03:56
  • The isEmpty() method returns true if the binary tree is null. This checks and returns the recursion when hitting the end of a leaf node.It appears to be functioning correctly as I can insert values into the tree testing for the null ends. – Alistair Dec 24 '18 at 04:06

1 Answers1

0

Fixed the error. Changing this.isEmpty() to searchTree.isEmpty(), checks the searchTree being processed. Previously it was check "this" which was a nullPtr. Still buggy, but at least it is producing something. Stuck on that for far too long.

Thanks

Alistair
  • 19
  • 5