二叉树,只打印一级(BFS)

时间:2013-10-15 19:51:11

标签: tree traversal

我想知道如何只打印某个级别的二叉树。我在这里读过很多关于BFS的问题但是没有找到关于printin的问题。

我应该如何将常见的BFS搜索更改为打印,比方说,只有这棵树的第2级:

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

Leve 2将是1,5,7,9。谢谢!

2 个答案:

答案 0 :(得分:1)

您需要在节点上拥有级别属性。然后当你在树上穿越时,你会问:

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
            }
         }
     }

答案 1 :(得分:0)

好的,我从一位教授那里得到了类似问题的答案。

在二叉搜索树中,找到特定级别的最小数字 (GenericTree和GenericQueue是课程的特定课程。我也翻译了整个练习,所以有些事情可能听起来很奇怪: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;
}                
相关问题