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

前端 未结 15 1415
情歌与酒
情歌与酒 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:33

    The following code will print each level of binary tree into new line:

    public void printbylevel(node root){
        int counter = 0, level = 0;
        Queue qu = new LinkedList();
    
        qu.add(root);
        level = 1;
        if(root.child1 != null)counter++;
        if(root.child2 != null)counter++;
    
         while(!qu.isEmpty()){
             node temp = qu.remove();
             level--;
             System.out.print(temp.val);
             if(level == 0 ){
                 System.out.println();
    
                 level = counter;
                 counter = 0;
             }
            if(temp.child1 != null){
                qu.add(temp.child1);
                counter++;
            }
            if(temp.child2 != null){
                qu.add(temp.child2);
                counter++;
            }
         }
    }
    

提交回复
热议问题