我希望了解如何打印二叉树中的特定层级。我在这里看到了许多关于BFS的问题,但没有一个是关于仅打印一层的。
如果我想打印该树的第2层,该如何更改普通的BFS搜索呢?
6
/ \
4 8
/ \ / \
1 5 7 9
2级将是1、5、7、9。谢谢!
我希望了解如何打印二叉树中的特定层级。我在这里看到了许多关于BFS的问题,但没有一个是关于仅打印一层的。
如果我想打印该树的第2层,该如何更改普通的BFS搜索呢?
6
/ \
4 8
/ \ / \
1 5 7 9
2级将是1、5、7、9。谢谢!
你的节点需要有一个 level 属性。然后当你在树上遍历时,你可以询问:
if (level == 2) //or whatever level you wish
{
...
}
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
}
}
}
我从一位教授那里得到了一个类似问题的答案。
在二叉搜索树中,找到特定层级上最小的数字。(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;
}