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,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
和上一题很类似,只不过输出的时候,需要“之”字形输出。
可以在上一层答案的基础上。对偶数层进行反转。
第一次用了两个队列,实现了,但比较慢。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List list = new ArrayList<List<Integer>>(); if( root == null) return list; Deque<TreeNode> queue = new LinkedList<TreeNode>(); Deque<TreeNode> queue1 = new LinkedList<TreeNode>(); queue.add(root); int dir = 0; while( !queue.isEmpty() ){ List ans = new ArrayList<Integer>(); int size = queue.size(); for( int i = 0;i<size;i++){ TreeNode node = null; if( dir == 0) node = queue.poll(); else node = queue.pollLast(); ans.add(node.val); if( dir == 0){ if( node.left != null) queue1.add(node.left); if( node.right != null) queue1.add(node.right); }else{ if( node.right != null) queue1.addFirst(node.right); if( node.left != null) queue1.addFirst(node.left); } } list.add(ans); queue.addAll(queue1); queue1.clear(); dir = (dir == 1?0:1); } return list; } }
但是优点在于不用递归和回溯
使用递归/回溯,速度和代码都会得到优化。
public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); helper(res, root, 1); for (int i = 0; i < res.size(); i++) if (i % 2 == 1) Collections.reverse(res.get(i)); return res; } private void helper(List<List<Integer>> res, TreeNode node, int level){ if (node == null) return; if (res.size() < level) res.add(new ArrayList<Integer>()); res.get(level-1).add(node.val); helper(res, node.left, level+1); helper(res, node.right, level+1); }