前言啊:工作幾年了,但以前大學學的演算法都快忘完了。趁著準備換工作的時間準備把演算法給撿起來,因為畢業後用的程式設計語言是Java所以準備都用Java語言來實現。
要求:有如下的二叉樹,請寫出一演算法實現分層從左至右列印二叉樹
預期結果:
root
left01 right01
left11 right11 left12 right12
代碼:
/** * */package my.algorithm.ch01;import java.util.LinkedList;import java.util.Queue;/** * 分層列印二叉樹 * * @Builder Create By Arno * @Email admin@happy-dev.com * @Time 2017年5月1日 */public class TreePrint { public static void print(BinaryTree root) { // 建立一個隊列用來存放節點 Queue<BinaryTree> queue = new LinkedList<BinaryTree>(); // 當前行列印的最右節點 BinaryTree last; // 下一行列印的最右節點 BinaryTree nlast = null; last = root; // 先將根放入隊列中 queue.add(root); // 隊列不為空白時,就一直迴圈poll直到隊列為空白 while (queue.size() > 0) { // 推出節點 BinaryTree nowTree = queue.poll(); // 如果當前節點有左節點,將左節點壓入隊列中 if (nowTree.hasLeftNode()) { queue.add(nowTree.getLeftNode()); nlast = nowTree.getLeftNode(); } // 如果當前節點有右節點,將左節點壓入隊列中 if (nowTree.hasRightNode()) { queue.add(nowTree.getRightNode()); nlast = nowTree.getRightNode(); } System.out.print(" " + nowTree.getValue()); // 噹噹前列印節點為當前行最右節點時換行 if (last.equals(nowTree)) { System.out.println(); last = nlast; } } } /** *測試用 * @param args */ public static void main(String[] args) { BinaryTree root = new BinaryTree(); root.setValue("root"); BinaryTree left01 = new BinaryTree("left01"); BinaryTree right01 = new BinaryTree("right01"); root.setLeftNode(left01); root.setRightNode(right01); BinaryTree left11 = new BinaryTree("left11"); BinaryTree right11 = new BinaryTree("right11"); left01.setLeftNode(left11); left01.setRightNode(right11); BinaryTree left12 = new BinaryTree("left12"); BinaryTree right12 = new BinaryTree("right12"); right01.setLeftNode(left12); right01.setRightNode(right12); print(root); }}class BinaryTree { /** * 節點值 */ private String value; /** * 左節點 */ private BinaryTree leftNode; /** * 右節點 */ private BinaryTree rightNode; /** * 預設無參構造 */ public BinaryTree() { } /** * 初始化value的構造 * * @param value */ public BinaryTree(String value) { this.value = value; } /** * @return the value */ public String getValue() { return value; } /** * @param value * the value to set */ public void setValue(String value) { this.value = value; } /** * @return the leftNode */ public BinaryTree getLeftNode() { return leftNode; } /** * @param leftNode * the leftNode to set */ public void setLeftNode(BinaryTree leftNode) { this.leftNode = leftNode; } /** * @return the rightNode */ public BinaryTree getRightNode() { return rightNode; } /** * @param rightNode * the rightNode to set */ public void setRightNode(BinaryTree rightNode) { this.rightNode = rightNode; } /** * 判斷是否有左節點 * * @return boolean */ public boolean hasLeftNode() { if (this.leftNode == null || this.leftNode.getValue() == null) { return false; } return true; } /** * 判斷是否有右節點 * * @return boolean */ public boolean hasRightNode() { if (this.rightNode == null || this.rightNode.getValue() == null) { return false; } return true; } }
測試結果:
記錄下,怕自己忘記啊