Java Solution with Queue, need a label to note the odd-even level.


  • 0
      public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res=new ArrayList<List<Integer>>();
        Queue<TreeNode> q=new LinkedList<TreeNode>();
        if(root==null)
             return res;
        q.offer(root);
        TreeNode node;
        int size;
        boolean label=true;
        while(q.peek()!=null){
            List<Integer> subres=new ArrayList<Integer>(); 
            size=q.size();
            for(int i=0;i<size;i++){
                node=q.poll();
                if(label)
                    subres.add(node.val);
                else subres.add(0,node.val);
                if(node.left!=null)
                    q.offer(node.left);
                if(node.right!=null)
                    q.offer(node.right);
             }
             
            label=!label;
            res.add(subres);
        }
        return res;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.