2016-04-25 118 views
0

我想寫一個函數來搜索我構建的樹上的一個值,我寫了一個可以正常工作的遞歸函數。現在我想改善我的運行時間,所以我想使用while循環來查找值。問題是我得到NullPointerException。我知道這棵樹是確定的,因爲在我執行搜索之前,我會打印所有的值。那麼我的代碼有什麼問題?用while循環搜索二叉樹

public void SearchByLoop(Node root,final int val){ 

     while(root != null || root.getVal() == val){ 

      if(root.getVal() < val) 

       root = root.getRightChild(); 

      else if(root.getVal() > val) 

       root = root.getLeftChild(); 

     } 

     if(root == null) 

      System.out.println("Couldn't find value " + val); 

     else if(root.getVal() == val) 

       System.out.println("Found value " + val); 

    } 

public class Main { 

public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    Tree theTree = new Tree(); 
    Random rand = new Random();//Create random variable. 
    int val = 0; 
    for(int i = 0 ; i < 100; i ++){ 

     val = rand.nextInt(151) + (0); 
     theTree.addNode(val,"a"); 
    } 
    theTree.inOrderTraverseTree(theTree.getRoot()); 
    theTree.SearchByLoop(theTree.getRoot(), 10); 

} 
} 

現在,inOrderTraverse方法打印所有的值,所以我知道這棵樹是確定的。可能是什麼問題?謝謝!

回答

3

這種情況

while(root != null || root.getVal() == val) 

會給你一個NullPointerException當root爲null。

你可能想

while(root != null && root.getVal() != val)