/*
public class TreeNode {
Objectval;
? ? TreeNodeleft;
? ? TreeNoderight;
? ? public TreeNode(Object val){
this.val = val;
? ? }
}*/
思路:加上last和nLast兩個(gè)變量,初始時(shí)都指向root, 然后每次遍歷時(shí),nLast指向當(dāng)前行的下一行的最后一個(gè)節(jié)點(diǎn),last指向當(dāng)前行的最后一個(gè)節(jié)點(diǎn)。如果last等于當(dāng)前打印的變量,即當(dāng)前打印的是最后一個(gè)節(jié)點(diǎn),輸出換行符,nLast 的值賦值給last;
/**
* 按層遍歷二叉樹(shù)
*/
public void searchTreeByCen(TreeNode root){
TreeNode last;
? ? TreeNode nLast;
? ? Queuequeue =new LinkedBlockingDeque<>();
? ? queue.add(root);
? ? last = root;
? ? nLast = root;
? ? while (!queue.isEmpty()){
TreeNode tmp = queue.poll();
? ? ? ? System.out.print(tmp.val+" ");
? ? ? ? if (tmp.left !=null){
queue.add(tmp.left);
? ? ? ? ? ? nLast = tmp.left;
? ? ? ? }
if (tmp.right !=null){
queue.add(tmp.right);
? ? ? ? ? ? nLast = tmp.right;
? ? ? ? }
if (last == tmp){
System.out.println();
? ? ? ? ? ? last = nLast;
? ? ? ? }
}
}