2012-10-07 40 views
1

我已經編寫了一個代碼,用於向二叉樹插入一個元素的泛型類型,它是按其名稱排序的。不要認爲這是正確的。java二叉樹插入函數非遞歸

public boolean insert(E e) { 
    BTNode temp = root; 
    if (root == null) { 
     root.setElement(e); 
    } 
    while (temp != null) 
    if (temp.element().getClass().getName().compareTo(e.getClass().getName()) < 0) { 
     temp = temp.getRight(); 
    } else { 
     temp = temp.getLeft(); 
    } 
    temp.setElement(e); 
    return true; 
} 

你能建議我更正嗎?

+1

問題是什麼? – Augusto

+4

在while語句後刪除分號。 –

+0

'temp' - 變量名稱的絕佳選擇。 –

回答

2

一種插件,需要創建一個新的節點。我現在沒有如何創建它們,因爲我沒有看到構造函數,但我建議沿着以下幾點:

public boolean insert(E e) {   
    if (root == null) { 
     root = new BTNode(); 
     root.setElement(e); //how would this work with a null root? 
     return true; //that's it, we're done (when is this ever false by the way?) 
    } 
    BTNode current = root; 
    while (true) { //brackets! indenting is important for readabilty 
     BTNode parent=current; 
     if (current.element().getClass().getName().compareTo(e.getClass().getName()) < 0) { 
      current = current.getRight(); 
      if(current==null) { //we don't have a right node, need to make one 
       current = new BTNode(); 
       parent.setRight(current); 
       break; //we have a new node in "current" that is empty 
      } 
     } else { 
      current= current.getLeft(); 
      if(current==null) { //we don't have a left node, need to make one 
       current = new BTNode(); 
       parent.setLeft(current); 
       break; //we have a new node in "current" that is empty 
      } 
     } 
    } 
    current.setElement(e); 
    return true; 
} 
-1

隨着艾瑪迪斯提到的,while循環不應該有一個分號結尾:

BTNode temp = root; 
    if (root == null) { 
     root.setElement(e); 
     return; 
    } 
    while (temp != null) 
    { 
     if (temp.element().getClass().getName().compareTo(e.getClass().getName()) < 0) { 
      if(temp.getRight() != null) 
      temp = temp.getRight(); 
      else 
      { 
       temp.createRight(e); 
       temp = null; //or break 
      } 
     } else { 
      if(temp.getLeft() != null) 
      temp = temp.getLeft(); 
      else 
      { 
       temp.createLeft(e); 
       temp = null; //or break 
      } 
     } 
    } 

    return true; 
+0

-1和正如我所說:然後行temp.setElement(e);總是空指針異常。 – weston

+0

另一種解決方案是捕捉異常並處理'catch'塊中的節點創建......雖然很醜陋...... –

+0

仍然錯誤'temp = null;'那麼這將如何阻止NPE? – weston