0

I'm adding values from an ArrayList of Strings to a BST and I'm coming up with a null pointer error on my line "tree.add(s);" and after tracing my code I can't figure out why this is happening. Can someone please help:

public class BinaryTree {

public Node root;
public BinaryTree tree;

private static class Node {
    Node left;
    Node right;
    String data;

    Node(String s) {
        left = null;
        right = null;
        data = s;
    }
}

public BinaryTree plantTree(ArrayList<String> dict) {

    Collections.shuffle(dict);

    for (String s : dict) {
        s.toUpperCase();
        System.out.print(s);
        tree.add(s);
    }

    System.out.print(tree);
    System.out.println();
    return tree;

}

/**
 * Creates an empty binary tree
 */
public BinaryTree() {
    root = null;
}

public boolean search(String data) {
    return (search(root, data));
}

private boolean search(Node node, String data) {
    if (node == null) {
        return (false);
    }

    if (data == node.data) {
        return (true);
    } else if (data.compareTo(node.data) > 0) {
        return (search(node.left, data));
    } else {
        return (search(node.right, data));
    }
}

public void add(String data) {
    root = add(root, data);
}

private Node add(Node node, String data) {
    if (node == null) {
        node = new Node(data);
    } else {
        if (data.compareTo(node.data) > 0) {
            node.left = add(node.left, data);
        } else {
            node.right = add(node.right, data);
        }
    }

    return (node);
}

}

0

1 Answer 1

1

You have to set the tree variable to something before using it. For example:

public BinaryTree plantTree(ArrayList<String> dict) {

    tree = new BinaryTree(); // important!

    Collections.shuffle(dict);

    for (String s : dict) {
        s.toUpperCase();
        System.out.print(s);
        tree.add(s);
    }

    System.out.print(tree);
    System.out.println();
    return tree;

}

Maybe tree should be a local variable of the method rather than an instance variable?

Sign up to request clarification or add additional context in comments.

2 Comments

Now I have one more question, how would I implement the toString() method to print out each value in the "tree". When I use System.out.print(tree) it prints out some weird value. I've seen it before and I believe I overrode the toString() method to print it out correctly.
It sounds like your toString is not correctly declared for it to override the default. You'll get a wider audience if you ask a new question though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.