Printing BFS (Binary Tree) in Level Order with Specific Formatting

前端 未结 15 1368
情歌与酒
情歌与酒 2020-12-04 13:00

To begin with, this question is not a dup of this one, but builds on it.

Taking the tree in that question as an example,

    1 
   / \\
  2   3
 /            


        
15条回答
  •  春和景丽
    2020-12-04 13:14

    why not keep sentinal in queue and check when all the nodes in current level are processed.

    public void printLevel(Node n) {
        Queue q = new ArrayBlockingQueue();
        Node sentinal = new Node(-1);
        q.put(n);
        q.put(sentinal);
        while(q.size() > 0) {
            n = q.poll();
            System.out.println(n.value + " "); 
            if (n == sentinal && q.size() > 0) {
               q.put(sentinal); //push at the end again for next level
               System.out.println();
            }
            if (q.left != null) q.put(n.left);
            if (q.right != null) q.put(n.right);
        }
    }
    

提交回复
热议问题