Ryan Sayles
Ryan Sayles

Reputation: 3431

Error adding Strings to a BST

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);
}

}

Upvotes: 0

Views: 273

Answers (1)

Joni
Joni

Reputation: 111259

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?

Upvotes: 1

Related Questions