題目:從上往下打印出二叉樹的每一個節點,同一層的結點按照從左往右的順序打印。java
解題思路:二叉樹的層序遍歷,在打印一個節點的時候,要把他的子節點保存起來打印第一層要把第二層的節點保存起來,node
打印第二層要把第三層的結點保存起來,以此類推。可使用的容器是隊列,每一次打印一個結點的時候,若是該結點有子結點,則把該點的子結點放到隊列的末尾,this
接下來從隊列的頭部取出最先進入隊列的節點,重複打印操做。spa
package Solution; import java.util.LinkedList; import java.util.Queue; public class No23PrintTreeFromTopToBottom { static class BinaryTreeNode{ int value; BinaryTreeNode left; BinaryTreeNode right; public BinaryTreeNode(int value,BinaryTreeNode left,BinaryTreeNode right){ this.value=value; this.left=left; this.right=right; } } public static void printBinaryTreeFromTopToBottom(BinaryTreeNode node){ if(node==null) throw new RuntimeException("invalid parameter"); Queue<BinaryTreeNode> queue=new LinkedList<BinaryTreeNode>(); queue.add(node); while(!queue.isEmpty()){ BinaryTreeNode currentNode=queue.poll(); System.out.print(currentNode.value +","); if(currentNode.left!=null) queue.add(currentNode.left); if(currentNode.right!=null) queue.add(currentNode.right); } } public static void main(String[] args) { BinaryTreeNode node1=new BinaryTreeNode(5,null,null); BinaryTreeNode node2=new BinaryTreeNode(7,null,null); BinaryTreeNode node3=new BinaryTreeNode(9,null,null); BinaryTreeNode node4=new BinaryTreeNode(11,null,null); BinaryTreeNode node5=new BinaryTreeNode(6,node1,node2); BinaryTreeNode node6=new BinaryTreeNode(10,node3,node4); BinaryTreeNode node7=new BinaryTreeNode(8,node5,node6); printBinaryTreeFromTopToBottom(node7); } }