题目
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree{3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
方法
对树进行层次遍历,然后将奇数行得到的结果进行反转。public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> list = new ArrayList<List<Integer>>(); if (root == null) { return list; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); while (!queue.isEmpty()) { int len = queue.size(); List<Integer> subList = new ArrayList<Integer>(); for(int i = 0; i < len; i++) { TreeNode curNode = queue.poll(); subList.add(curNode.val); if (curNode.left != null) { queue.offer(curNode.left); } if (curNode.right != null) { queue.offer(curNode.right); } } list.add(subList); } int i = 0; for (List<Integer> subList: list) { if (i % 2 == 1) { Collections.reverse(subList); } i++; } return list; }