/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>> ();
if (root==null) return res;
ArrayList<Integer> temp = new ArrayList<Integer> ();
Queue<TreeNode> queue = new LinkedList<TreeNode> ();
queue.add(root);
boolean flag = true;
int currentcnt = 1;
int nextcnt = 0;
while (!queue.isEmpty()) {
TreeNode current = queue.remove();
currentcnt--;
temp.add(current.val);
if (current.left!=null) {
queue.add(current.left);
nextcnt++;
}
if (current.right!=null) {
queue.add(current.right);
nextcnt++;
}
if (currentcnt==0) {
if (!flag) Collections.reverse(temp);
flag=!flag;
res.add((ArrayList<Integer>) temp.clone());
temp.clear();
currentcnt = nextcnt;
nextcnt = 0;
}
}
return res;
}
}
1. similar to Q 32.
回复删除2. 用boolean flag标记方向,如果从右往左,需要reverse temp.