103.Binary Tree Zigzag Level Order Traversal

题目链接

题目大意:二叉树层序z字型的方式打印输出,即奇数行正常打印,偶数行倒序打印。例子如下:

法一:利用102的层序遍历,然后用Collections.reverse(list),在偶数行的时候将list翻转即可。代码如下(耗时2ms):

 1     public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
 2         List<List<Integer>> res = new ArrayList<List<Integer>>();
 3         if(root == null) {
 4             return res;
 5         }
 6         Queue<TreeNode> q = new LinkedList<TreeNode>();
 7         q.offer(root);
 8         int level = 0;
 9         while(!q.isEmpty()) {
10             level++;
11             int cnt = q.size();
12             List<Integer> listLevel = new ArrayList<Integer>();
13             for(int i = 0; i < cnt; i++) {
14                 TreeNode tmp = q.poll();
15                 listLevel.add(tmp.val);
16                 if(tmp.left != null) {
17                     q.offer(tmp.left);
18                 }
19                 if(tmp.right != null) {
20                     q.offer(tmp.right);
21                 }
22             }
23             //对list进行翻转
24             if(level % 2 == 0)
25                 Collections.reverse(listLevel);
26             res.add(new ArrayList<Integer>(listLevel));
27         }
28         return res;
29     }
View Code

 

posted on 2018-05-08 14:54  二十年后20  阅读(151)  评论(0编辑  收藏  举报

导航