2012-03-19 77 views
0

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

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

你必须在使用前设置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应该是方法的局部变量而不是实例变量?

+0

这解决了我的问题。非常感谢! – 2012-03-19 23:47:12

+0

现在我还有一个问题,我将如何实现toString()方法来打印出“树”中的每个值。当我使用System.out.print(树)时,它打印出一些奇怪的值。我以前见过它,我相信我会覆盖toString()方法将其正确打印出来。 – 2012-03-20 18:45:28

+0

听起来像你的'toString'没有正确声明它来覆盖默认值。如果你问一个新问题,你会得到更多的观众。 – Joni 2012-03-20 23:11:43