按層打印二叉樹--每行打印一層


一,問題介紹

 給定一棵二叉樹,按照層序遍歷的順序打印二叉樹。但是要求,每一行打印一層數據。

 

二,算法分析

借助二叉樹的層序遍歷來實現(使用隊列的先入先出性質保證打印的順序)。

為了按行打印 :需要額外兩個變量,一個變量用來保存當前層 還未打印的結點個數,另一個變量保存下一層待打印的結點個數。

二叉樹層序遍歷參考:http://www.cnblogs.com/hapjin/p/5409921.html

層序打印參考:

 1 public void printTree(BinaryNode<T> root){
 2         if(root == null)
 3             return;
 4         Queue<BinaryNode<T>> queue = new LinkedList<>();
 5         
 6         int current;//當前層 還未打印的結點個數
 7         int next;//下一層結點個數
 8         
 9         queue.offer(root);
10         current = 1;
11         next = 0;
12         while(!queue.isEmpty()){
13             BinaryNode<T> currentNode = queue.poll();
14             System.out.printf("%-4d", currentNode.element);
15             current--;
16             
17             if(currentNode.left != null){
18                 queue.offer(currentNode.left);
19                 next++;
20             }
21             if(currentNode.right != null){
22                 queue.offer(currentNode.right);
23                 next++;
24             }
25             if(current ==0){
26                 System.out.println();
27                 current = next;
28                 next = 0;
29             }
30         }
31     }

 

原文:https://www.cnblogs.com/hapjin/p/5564552.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM