Simple Accepted JAVA solution (needn't change much from the related problems)


  • 0
    F

    Use almost the same way we solving "Binary Tree Right Side View", "Binary Tree Level Order Traversal" and "Binary Tree Level Order Traversal ||".
    For this specific problem, just add a boolean flag to determine left-to-right printing or in another way, and then reverse the flag!

    public class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            Queue<TreeNode> q = new LinkedList<TreeNode>();
            q.add(root);
            List<List<Integer>> output = new ArrayList<List<Integer>>();
            boolean fromLeft = true; // if we directly add this row to output, or need to reverse.
            while(q.peek()!= null){
                List<Integer> row = new ArrayList<Integer>();
                Stack<Integer> verseRow = new Stack<Integer>();
                int levelSize = q.size();
                for(int i=0; i<levelSize; i++){
                    TreeNode node = q.poll();
                    if(fromLeft){
                        row.add(node.val);
                    }else{
                        verseRow.push(node.val);
                    }
                    if(node.left != null){q.add(node.left);}
                    if(node.right != null){q.add(node.right);}
                }
                if(fromLeft){
                    fromLeft = false; // next level will be from right
                }else{
                    // reverse the row
                    while(!verseRow.isEmpty()){
                        row.add(verseRow.pop());
                    }
                    fromLeft= true; // next level will be from left
                }
                output.add(row);
            }
             return output;
        }
    }

Log in to reply
 

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