從上到下按層打印二叉樹,同一層結點從左至右輸出。每一層輸出一行。java
層次遍歷node
public class Solution { ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> list = new ArrayList<>(); depth(pRoot, 1, list); return list; } private void depth(TreeNode root, int depth, ArrayList<ArrayList<Integer>> list) { if(root == null) return; if(depth > list.size()) list.add(new ArrayList<Integer>()); list.get(depth -1).add(root.val); depth(root.left, depth + 1, list); depth(root.right, depth + 1, list); } }
import java.util.*; public class Solution { static ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) { return levelorder(pRoot); } public static ArrayList<ArrayList<Integer>> levelorder(TreeNode root) { Queue<TreeNode> queue = new LinkedList<>(); ArrayList<ArrayList<Integer>> result = new ArrayList<>(); if(root == null) return result; queue.offer(root); // 首先將根節點root入隊 while (!queue.isEmpty()) {// Queue不爲空則循環 ArrayList<Integer> node = new ArrayList<>();// 保存每一層節點的值 int length = queue.size();// 每一層的節點數目 while (length > 0) { TreeNode tree = queue.poll(); if (tree.left != null) { queue.offer(tree.left); } if (tree.right != null) { queue.offer(tree.right); } node.add(tree.val); length--; } // 循環結束後,獲得的Queue爲下一層作準備,node爲本層遍歷結果 result.add(node); } return result; } }