将字符串添加到BST时出错

时间:2012-03-19 23:24:59

标签: java binary-search-tree

我正在将字符串的ArrayList中的值添加到BST中,并且我在我的行“tree.add(s);”上出现空指针错误。在跟踪我的代码后,我无法弄清楚为什么会发生这种情况。有人可以帮忙:

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

}

1 个答案:

答案 0 :(得分:1)

在使用之前,您必须将tree变量设置为某个变量。例如:

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;

}

也许tree应该是方法的局部变量而不是实例变量?