Easy-To-Understand Java Solution using LinkedList


  • 0
    public class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            if(root==null)
                return res;
            LinkedList<TreeNode> lst = new LinkedList<TreeNode>();
            boolean reverse = false;
            lst.add(root);
            while(!lst.isEmpty()) {
                List<Integer> subLst = new ArrayList<Integer>();
                int size = lst.size();
                while(size-- > 0) {
                    TreeNode node = reverse ? lst.pollLast() : lst.pollFirst();
                    subLst.add(node.val);
                    if(reverse) {
                        if(node.right!=null)
                            lst.offerFirst(node.right);
                        if(node.left!=null)
                            lst.offerFirst(node.left);
                    } else {
                        if(node.left!=null)
                            lst.offerLast(node.left);
                        if(node.right!=null)
                            lst.offerLast(node.right);
                    }
                }
                res.add(subLst);
                reverse = !reverse;
            }
            return res;
        }
    }

Log in to reply
 

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