[解题思路]
记录下一层元素个数,这样每次遍历时就知道何时结束,只需一个queue
用一个count来计数每一层的node的个数,
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if(root == null) return result; LinkedList<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); //用来计数每一层有多少个Node int nextLevelCount = 1; while(!queue.isEmpty()){ int curLevel = nextLevelCount; nextLevelCount = 0; ArrayList<Integer> lvl = new ArrayList<Integer>(); // 此循环就是根据nextLevelCount来从队列里拿出多少个Node for(int i = 0; i < curLevel; i++){ TreeNode tmp = queue.poll(); lvl.add(tmp.val); if(tmp.left != null){ queue.add(tmp.left); nextLevelCount++; } if(tmp.right != null){ queue.add(tmp.right); nextLevelCount++; } } result.add(lvl); } return result; } }
用两个queue的方法
1 public class Solution { 2 public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) { 3 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); 4 if(root == null) 5 return res; 6 7 Queue<TreeNode> curlvl = new LinkedList<TreeNode>(); 8 9 10 curlvl.add(root); 11 12 while(!curlvl.isEmpty()){ 13 ArrayList<Integer> output = new ArrayList<Integer>(); 14 Queue<TreeNode> nextlvl = new LinkedList<TreeNode>(); 15 while(!curlvl.isEmpty()){ 16 TreeNode n = curlvl.poll(); 17 output.add(n.val); 18 if(n.left != null){ 19 nextlvl.add(n.left); 20 } 21 if(n.right != null){ 22 nextlvl.add(n.right); 23 } 24 } 25 res.add(output); 26 curlvl = nextlvl; 27 } 28 return res; 29 } 30 }
ref:http://www.cnblogs.com/feiling/p/3258537.html