I'd like to know how could i do to print only a certain level of a binary tree. I've read many questions here about BFS but found none about printin just one level.
How should i change a common BFS search to print, lets say, only level 2 of this tree:
6
/ \
4 8
/ \ / \
1 5 7 9
Leve 2 would be 1, 5, 7, 9. Thank you!
You need to have a level property on your Node. And then when you traverse on the tree, you ask:
if (level == 2) //or whatever level you wish
{
...
}
Here is a good example: Find all nodes in a binary tree on a specific level (Interview Query)
If there is no level on the Node and you can't change it, then you can make it as a global variable in the method you make the checks - not preferable but one more solution. I haven't check this answer in code, but I believe it should be very close to the solution.
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
}
}
}
Ok i got the answer from a professor for a similar problem.
In a binary search tree, find the lowest number on a certain level (GenericTree and GenericQueue are specific classes of the course. Also i traslated the whole exercise so some things may sound weird or not :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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With