Easy java solution with BFS


  • 0
    V
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> result = new ArrayList<>();
            if(root == null)
            {
                return result;
            }
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            boolean isLeftToRight = true;
            while (!queue.isEmpty())
            {
                int size = queue.size();
                List<Integer> list = new ArrayList<>();
                
                for (int j = 0; j <size ; j++) {
                    TreeNode currentNode = queue.poll();
                    if(currentNode.left != null)
                    {
                        queue.offer(currentNode.left);
                    }
                    if(currentNode.right != null)
                    {
                        queue.offer(currentNode.right);
                    }
                    list.add(currentNode.val);
                }
                if(!isLeftToRight)
                {
                    Collections.reverse(list);
                }
                result.add(list);
                isLeftToRight = !isLeftToRight;
            }
            
            return result;
        }
    

Log in to reply
 

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