2 Deques JAVA


  • 0
    I
    /**
     * 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<Integer>> res = new ArrayList<List<Integer>>();
            if(null == root) return res;
            
            Deque<TreeNode> q = new LinkedList<TreeNode>();
            Deque<TreeNode> p = new LinkedList<TreeNode>();
            q.offerLast(root);
            int size = q.size();
            boolean reverse = true;
            while(!q.isEmpty()) {
                
                List<Integer> l = new ArrayList<Integer>();
                while(!q.isEmpty()) {
                    TreeNode node = q.pollFirst();
                    
                    if(null != node.left) {
                        p.offerLast(node.left);
                    }
                    if(null != node.right) {
                        p.offerLast(node.right);
                    }
                    
                    l.add(node.val);
                }
                
                if(!reverse) Collections.reverse(l);
                res.add(l);
                reverse = !reverse;
                q = p;
                p = new LinkedList<TreeNode>();
            }
            
            return res;
        }
    }
    

Log in to reply
 

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