2011-05-26 60 views
1

嘿傢伙, 我已經實現了一棵樹。對我來說,它應該正常工作,但因爲我在這裏,所以沒有。爲了記錄,我的樹的類型是City,它有三個字段,其中一個是您將看到的名稱。看看我的代碼:創建樹並添加值

void add(City added, City parent){ 
//added is what is going to be added and child of parent. I first find parent in tree 
//search method is coming after 
    TreeNode<City> parentNode = search(parent,this); 
    if (parentNode.hasLeftChild() && parentNode.getLeftChild().getCity().equals(parent)) 
     parentNode = parentNode.getLeftChild(); 
    else if (parentNode.hasNextSibling() && parentNode.getNextSibling().getCity().equals(parent)) 
     parentNode = parentNode.getNextSibling(); 
    else if (!parentNode.hasLeftChild()) 
     parentNode.setLeftChild(new TreeNode<City>(added,null,null)); 
    else { 
     TreeNode<City> next = parentNode.getLeftChild(); 
     while(next.hasNextSibling()) 
      next = next.getNextSibling(); 
     next.setNextSibling(new TreeNode<City>(added,null,null)); 
    } 
} 

public TreeNode<City> search(City parent, TreeNode<City> t){ 
    if (t.getCity().equals(parent)) 
     return t; 
    else if (t.hasLeftChild()) 
     return search(parent,t.getLeftChild()); 
    else 
     return search(parent,t.getNextSibling()); 
} 

我一直在採取nullpointerexception,不知道該怎麼做。任何人都有更好的想法來搜索一個元素並添加它。或者至少有一個網站讓我學習這個狗屎?

+0

什麼是NPE的堆棧跟蹤?它應該告訴你它發生的確切的代碼行,這使得對每個人來說,排除故障變得容易很多。 – 2011-05-26 19:07:26

+0

是的,我看到問題出在哪裏。當我爲leftchild調用方法時,如果最終的孩子不是我正在尋找的孩子,它會給出錯誤。我想知道如何解決它 – 2011-05-26 19:20:22

回答

0

您必須測試您的樹爲空的基本情況,以便您試圖添加的節點將真正成爲樹的根。

+0

我保證不會發生。樹將在其中的一個城市中創建 – 2011-05-26 18:59:54