Meta interview question

Print a binary tree level by level

Interview Answers

Anonymous

Nov 17, 2013

public Void BFS() { Queue q = new Queue(); q.Enqueue(root);//You don't need to write the root here, it will be written in the loop while (q.count > 0) { Node n = q.DeQueue(); Console.Writeln(n.Value); //Only write the value when you dequeue it if (n.left !=null) { q.EnQueue(n.left);//enqueue the left child } if (n.right !=null) { q.EnQueue(n.right);//enque the right child } } }

1

Anonymous

Dec 11, 2013

See oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/

Anonymous

Dec 11, 2013

Oops. I meant this: oj.leetcode.com/problems/binary-tree-level-order-traversal/

Anonymous

Apr 13, 2016

Improving THY answer: public Void BFS(Node root) { if(root == null) return; Queue q = new Queue(); q.Enqueue(root);//You don't need to write the root here, it will be written in the loop while (!q.empty()) { Node current = q.DeQueue(); Console.Writeln(n.Value); //Only write the value when you dequeue it if (n.left !=null){ q.EnQueue(n.left);} //enqueue the left child if (n.right !=null) { q.EnQueue(n.right); } //enque the right child q.pop(); // popping since we used the dequed node } }

Anonymous

Dec 11, 2013

Darn, can't edit comments. The oj.leetcode link links to something similar but not exactly.