Daily Coding Problem: Problem #994

import java.util.*

/**
 * This problem was asked by Microsoft.
 * Print the nodes in a binary tree level-wise. For example, the following should print 1, 2, 3, 4, 5.
  1
 / \
2   3
   / \
  4   5
 * */
class Problem_994 {
    /*
    * solution: BFS, Time:O(n), Space:O(n)
    * */
    fun printLevel(node: Node) {
        val queue = LinkedList<Node>()
        queue.offer(node)
        while (queue.isNotEmpty()) {
            //pop from head
            val cur = queue.pop()
            //println it out
            println(cur.value)
            //add into tail
            if (cur.left != null) {
                queue.offer(cur.left)
            }
            //add into tail
            if (cur.right != null) {
                queue.offer(cur.right)
            }
        }
    }
}

 

posted @ 2021-09-12 10:36  johnny_zhao  阅读(17)  评论(0编辑  收藏  举报