2013-10-15 54 views
2

我想知道如何才能打印僅二進制樹的特定級別。我在這裏閱讀了許多有關BFS的問題,但只有一個層面沒有發現關於printin的問題。二進制樹,僅打印一個級別(BFS)

我應該如何改變一個共同的BFS搜索打印,可以說,只有這棵樹的2級:

6 
/\ 
4 8 
/\/\ 
1 5 7 9 

LEVE 2是1,5,7,9,謝謝!

+0

跟蹤你當前的級別;當它達到2時終止。 –

+0

這很明顯,但我找不到使用常規BFS的方式,它使用節點處理隊列, t區分不同級別,它只是按照BFS順序排列和處理它們 我所有的東西都是一些奇怪的解決方案,它檢查每個級別應該有的節點數量,但是當它崩潰時我想到一個非滿樹 – nitrnitr

+0

一種方法是排列{level,node}的元組,而不僅僅是{node}。 –

回答

0

好吧,我得到了從一個類似問題的教授的答案。

在二叉搜索樹,找到在一定程度 (GenericTree和GenericQueue是當然的特定類別的最低數量也我traslated整個演習所以有些東西可能聽起來怪異或不:P。

public int calculateMinimum(BinaryTree<Integer> tree, int n){ 
    GenericQueue<BinaryTree<Integer>> queue = new GenericQueue<BinaryTree<Integer>>(); 
    queue.push(tree); 
    queue.push(new BinaryTree<Integer>(-1)); 
    int nActual = 0; //actual level 
    while (!queue.isEmpty()){ 
     tree = queue.pop(); 
     if (nActual == n){ 
      int min = tree.getRootData(); 
      while (!queue.isEmpty()){ 
       tree = queue.pop(); 
       if (!tree.getRootData().equals(-1) && (tree.getRootData()<min)) 
        min = tre.getRootData(); 
      } 
      return min; 
     } 
     if (!tree.getLeftChild().getRootData() == null)) 
      queue.push(tree.getLeftChild()); 
     if (!tree.getRightChild().getRootData() == null)) 
      queue.push(tree.getRightChild()); 
     if ((tree.getRootData().equals(-1) && (!queue.isEmpty())){ 
      nActual++; 
      queue.push(new BinaryTree<Integer>(-1)); 
     } 
    } 
    return -1; 
}     
1

您需要在Node上擁有一個關卡屬性。然後當你遍歷在樹上,你問:

if (level == 2) //or whatever level you wish 
{ 
    ... 
} 

這裏是一個很好的例子:Find all nodes in a binary tree on a specific level (Interview Query)

如果在節點沒有水平,你不能改變它,那麼你可以讓它作爲您製作支票的方法中的全局變量 - 不是更可取,而是更多的解決方案。我沒有在代碼中檢查這個答案,但我認爲它應該非常接近解決方案。

e.g:

int level = 0; 

    public void PrintOneLevelBFS(int levelToPrint)  
    {  
     Queue q = new Queue(); 
     q.Enqueue(root); //Get the root of the tree to the queue. 

     while (q.count > 0) 
     { 
      level++; //Each iteration goes deeper - maybe the wrong place to add it (but somewhere where the BFS goes left or right - then add one level). 
      Node node = q.DeQueue(); 

      if (level == levelToPrint) 
      { 
       ConsoleWriteLine(node.Value) //Only write the value when you dequeue it 
      } 

      if (node.left !=null) 
      { 
       q.EnQueue(node.left); //enqueue the left child 
      } 
      if (n.right !=null) 
      { 
       q.EnQueue(node.right); //enqueue the right child 
      } 
     } 
    } 
+0

謝謝Misha,這是一個很好的解決方案,但如果你不能在節點上擁有該屬性呢? 我在計算機科學大學,我認爲這可能是一個可能的測試練習。 – nitrnitr

+0

@Pphax我編輯了答案 - 檢查它:​​) –

+0

嗯我不認爲它會工作。它會增加每次循環運行的水平(1循環= 1節點,然後,不是爲每個級別)。 – nitrnitr