跟之前的解法一模一样Binary Tree Level Order Traversal I,II 不赘述
public class Solution { public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); if(root==null) return res; LinkedList<TreeNode> q = new LinkedList<TreeNode>(); int curNum = 1, nextNum = 0; boolean rv =false; ArrayList<Integer> cl = new ArrayList<Integer>(); q.add(root); while(!q.isEmpty()){ curNum--; TreeNode n = q.poll(); cl.add(n.val); if(n.left!=null){ q.add(n.left); nextNum++; } if(n.right!=null){ q.add(n.right); nextNum++; } if(curNum==0){ if(rv){ Collections.reverse(cl); } rv = !rv; res.add(cl); cl = new ArrayList<Integer>(); curNum= nextNum; nextNum=0; } } return res; } }
Binary Tree Zigzag Level Order Traversal
原文:http://www.cnblogs.com/jiajiaxingxing/p/4565046.html