My 3ms Java solution with Deque.


  • 0
    A

    Use deque and peek last as level side node.

     public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> resList = new ArrayList<>();
    //    Queue<TreeNode> queue = new LinkedList<>();
        Deque<TreeNode> deque = new ArrayDeque<>();
        if(root!=null)deque.offer(root);
        TreeNode sideNode = root;
        List<Integer> levelList = new ArrayList<>();
        int level =1;
          while(!deque.isEmpty()&&sideNode!=null){        
          TreeNode node = deque.poll();
          if(level%2!=0)
            levelList.add(0,node.val);     
          else
          levelList.add(node.val);     
            if(node.right!=null) deque.add(node.right);    
            if(node.left!=null) deque.add(node.left);  
          if(node.equals(sideNode)){
            resList.add(levelList);
            levelList = new ArrayList<>();
            sideNode = deque.peekLast();
            level++;
          }
        }
    
          return resList;
      
      }
    

Log in to reply
 

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