102. Binary Tree Level Order Traversal
BSF用queue,DSF用stack
1 public List<List<Integer>> levelOrder(TreeNode root) { 2 List<List<Integer>> res = new ArrayList<List<Integer>>(); 3 if(root == null) { 4 return res; 5 } 6 LinkedList<TreeNode> queue = new LinkedList<TreeNode>(); 7 queue.offer(root); 8 int lastLevelCnt = 1; 9 int curLevelCnt = 0; 10 List<Integer> curLevel = new ArrayList<Integer>(); 11 while(!queue.isEmpty()) { 12 TreeNode curNode = queue.poll(); 13 curLevel.add(curNode.val); 14 lastLevelCnt--; 15 if(curNode.left != null) { 16 queue.add(curNode.left); 17 curLevelCnt++; 18 } 19 if(curNode.right != null) { 20 queue.add(curNode.right); 21 curLevelCnt++; 22 23 } 24 if(lastLevelCnt == 0) { 25 res.add(curLevel); 26 lastLevelCnt = curLevelCnt; 27 curLevelCnt = 0; 28 curLevel = new ArrayList<Integer>(); 29 } 30 } 31 return res; 32 }