2012-03-19 76 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