Loading...
Engaged employer
Print a Binary Tree level by level
Anonymous
Use queue to do a BFS on the tree
do a BFS and print: printBSTLevels(Node n) { Queue q = new Queue(); q.enqueue(n); while(!q.isEmpty()) { n = q.dequeue(); if(n.left != null) q.enqueue(n.left); if(n.right != null) q.enqueue(n.right); System.out.println(n.val); } }
The above solution is correct but it doesn't print each level on the same line. You can use two stacks or queues to do that.
Check out your Company Bowl for anonymous work chats.
Get actionable career advice tailored to you by joining more bowls.
Stay ahead in opportunities and insider tips by following your dream companies.
Get personalised job recommendations and updates by starting your searches.