这道题目,一刷用Queue就可以了

 

 1 class Solution {
 2     public List<List<Integer>> levelOrder(TreeNode root) {
 3            List<List<Integer>> res = new ArrayList<>();
 4         if (root == null) {
 5             return res;
 6         }
 7         
 8         Queue<TreeNode> queue = new LinkedList<>();
 9         queue.offer(root);
10         while (!queue.isEmpty()) {
11             int size = queue.size();
12             List<Integer> sub = new ArrayList<>();
13             for (int i = 0; i < size; i++) {
14                 TreeNode cur = queue.poll();
15             if (cur.left != null) {
16                 queue.offer(cur.left);
17             }
18             if (cur.right != null) {
19                 queue.offer(cur.right);
20             }
21             sub.add(cur.val);
22             }
23             res.add(new ArrayList<Integer>(sub));
24         }
25         return res;
26     }
27 }

 

posted on 2018-03-02 12:41  mayinmiao  阅读(84)  评论(0编辑  收藏  举报