Binary Tree Zigzag Level Order Traversal

跟之前的解法一模一样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;
    }
}

 

posted @ 2015-06-10 04:43  世界到处都是小星星  阅读(137)  评论(0编辑  收藏  举报