2011-11-21 43 views
0

所以我打印一個B級的樹。一個節點最多有3個密鑰和最多4個子節點,它是典型的2-3-4樹。除了當我添加「2 5 8 1 3 6 9 7 11 12 10 4」之外,代碼對大多數內容都能正常工作。具體來說,問題是我的隊列中的推(2 5)和(11)然後計數(2 5)個孩子。之後,我去流行它的孩子,但是(11)阻礙了它並將其擰緊。使用bfs打印樹。快速修復所需

void BFS(TwoThreeFourTree tree, Node start) 
{ 
    ArrayList<String> level = new ArrayList<String>(); 
    int levCount = 0; 

    LinkedList<Node> queue = new LinkedList<Node>(); 
    queue.add(start); 
    level.add("(" + keys(start) + ")"); 
    while (!queue.isEmpty()) 
    { 
     Node vertix = queue.remove(); 
     for (Node child : vertix.child) 
     { 
      if (child == null) break; 
      queue.add(child); 
      levCount++; 
     } 

     String allChild = ""; 
     Node temp[] = new Node[levCount]; 
     while (levCount > 0) 
     { 
      temp[levCount - 1] = queue.remove(); 
      allChild = allChild.concat("(" + keys(temp[levCount - 1]) + ")"); 
      levCount--; 
     } 
     for (Node child : temp) 
      queue.addFirst(child); 
     if (levCount == 0 && allChild != "") 
      level.add(allChild); 
    } 
    for (String stuff : level) 
    { 
     System.out.println(stuff); 
    } 
    System.out.println("----------------------"); 
} 
+1

耶!免費閱讀someones無證代碼!時間喝一杯! – regality

回答

0

是的,問題是你的算法不正確。當你開始迭代循環並且你的隊列是非空的時候,你在隊列的末尾添加'levCount'節點,但是你從開頭(queue.remove())獲取'levCount'節點,並且它們有與您添加到最後的節點無關。這不是平常的/真正的BFS搜索,而是它的一個錯誤版本。普通BFS搜索如下僞代碼:

while (queue is not empty) 
    node = remove first from queue 
    <process/print node> 
    for each child of node 
     push child to queue 

如果你的願望是處理每個水平在BFS的方式,你需要不同的算法。