A more simple solution


  • 0
    S

    use level to determine the result order

     public class Solution {
             public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
                    List<List<Integer>> list = new ArrayList<>();
                    if (root == null) return list;
                    Queue<TreeNode> q = new LinkedList<>();
                    q.offer(root);
                    int level = 0;
    
                    while (!q.isEmpty()) {
                    int size = q.size();
                    List<Integer> cur = new ArrayList<>();
                
                    for (int i = 0; i < size; i++) {
                         TreeNode node = q.poll();
                          if (level % 2 == 1) {
                                cur.add(0, node.val);
                          } else {
                                cur.add(node.val);
                         }
                    
                         if (node.left != null) q.offer(node.left);
                         if (node.right != null) q.offer(node.right);
                   }
                   list.add(cur);
                   level++;
              }
            return list;
        }
    }
    
    
    • list item

Log in to reply
 

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