1. 程式人生 > >二叉樹按層遍歷

二叉樹按層遍歷

traverse 結束 == 正在 表示 this 根節點 binary args

/*         
 * 二叉樹的層次遍歷      
 *     1.首先將根節點放入隊列中。 
       2.當隊列為非空時,循環執行步驟3到步驟5,否則執行6; 
       3.出隊列取得一個結點,訪問該結點; 
       4.若該結點的左子樹為非空,則將該結點的左子樹入隊列; 
       5.若該結點的右子樹為非空,則將該結點的右子樹入隊列; 
       6.結束。
  */  

import java.util.Queue;

public class BinaryTree<T> { private T data; private BinaryTree<T> left;
private BinaryTree<T> right; private BinaryTree(T data) { this.data = data; } public BinaryTree() { } //層次遍歷 public static void levelTraverse(BinaryTree root) { if(root==null) { try { throw new Exception("二叉樹為空"); }
catch (Exception e) { e.printStackTrace(); } }else { Queue<BinaryTree> queue = new Queue<BinaryTree>(); queue.enqueue(root); while(!queue.isEmpty()) { root = queue.dequeue(); System.out.print(root.data
+ " "); if(root.left != null) queue.enqueue(root.left); if(root.right != null) queue.enqueue(root.right); } } } //換行層次遍歷 public static void newLevelTraverse(BinaryTree root) { BinaryTree last = new BinaryTree(); BinaryTree nlast = new BinaryTree(); if(root==null) { try { throw new Exception("二叉樹為空"); }catch (Exception e) { e.printStackTrace(); } }else { Queue<BinaryTree> queue = new Queue<BinaryTree>(); queue.enqueue(root); last = root;//last表示正在打印的當前行 的最右節點 nlast = root;//nlast表示下一行的最右節點,nlast節點每次跟蹤記錄最先加入隊列的節點 while(!queue.isEmpty()) { root = queue.dequeue(); System.out.print(root.data+" "); if(root.left != null) { queue.enqueue(root.left); nlast = root.left; } if(root.right != null) { queue.enqueue(root.right); nlast = root.right; } //如果當前輸出節點root是最右節點last,那麽換行 if(last == root) { System.out.println(); last = nlast;//last節點更新為nlast節點 } } } } public static void main(String[] args) { BinaryTree b1 = new BinaryTree(1); BinaryTree b2 = new BinaryTree(2); BinaryTree b3 = new BinaryTree(3); BinaryTree b4 = new BinaryTree(4); BinaryTree b5 = new BinaryTree(5); BinaryTree b6 = new BinaryTree(6); BinaryTree b7 = new BinaryTree(7); BinaryTree b8 = new BinaryTree(8); b1.left = b2; b1.right = b3; b2.left = b4; b3.left = b5; b3.right = b6; b5.left = b7; b5.right = b8; //層次遍歷二叉樹 BinaryTree.levelTraverse(b1);
     //換行層次遍歷
BinaryTree.newLevelTraverse(b1); } }

二叉樹按層遍歷