劍指offer{面試題23:從上往下列印二叉樹}
阿新 • • 發佈:2018-12-10
簡單的二叉樹層序遍歷,利用佇列的先進先出結構
關於層序遍歷層序遍歷
貼程式碼
public class Test23 { /** * 二叉樹的樹結點 */ public static class BinaryTreeNode { int value; BinaryTreeNode left; BinaryTreeNode right; } /** * 從上往下打印出二叉樹的每個結點,向一層的結點按照從左往右的順序列印。 * 例如下的二叉樹, * 8 * / \ * 6 10 * / \ / \ * 5 7 9 11 * 則依次打印出8、6、10、5、3 、9、11. * * @param root 樹的結點 */ public static void printFromToBottom(BinaryTreeNode root) { // 當結點非空時才進行操作 if (root != null) { // 用於存放還未遍歷的元素 Queue<BinaryTreeNode> list = new LinkedList<>(); // 將根結點入隊 list.add(root); // 用於記錄當前處理的結點 BinaryTreeNode curNode; // 佇列非空則進行處理 while (!list.isEmpty()) { // 刪除隊首元素 curNode = list.remove(); // 輸出隊首元素的值 System.out.print(curNode.value + " "); // 如果左子結點不為空,則左子結點入隊 if (curNode.left != null) { list.add(curNode.left); } // 如果右子結點不為空,則左子結點入隊 if (curNode.right != null) { list.add(curNode.right); } } } }