與樹的前中后序遍歷的DFS思想不同,層次遍歷用到的是BFS思想。一般DFS用遞歸去實現(也可以用棧實現),BFS需要用隊列去實現。
層次遍歷的步驟是:
1.對於不為空的結點,先把該結點加入到隊列中
2.從隊中拿出結點,如果該結點的左右結點不為空,就分別把左右結點加入到隊列中
3.重復以上操作直到隊列為空
1 public class Solution{
2 class TreeNode { 3 int val; 4 TreeNode left; 5 TreeNode right; 6 TreeNode(int x) { val = x; } 7 } 8 public static void LaywerTraversal(TreeNode root){ 9 if(root==null) return; 10 LinkedList<TreeNode> list = new LinkedList<TreeNode>(); 11 list.add(root); 12 TreeNode currentNode; 13 while(!list.isEmpty()){ 14 currentNode=list.poll(); 15 System.out.println(currentNode.val); 16 if(currentNode.left!=null){ 17 list.add(currentNode.left); 18 } 19 if(currentNode.right!=null){ 20 list.add(currentNode.right); 21 } 22 } 23 } 24 }