Simple 20line Java solution


  • -1
    C
    public class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            if(root==null) return result;
            int toRight = 1;
            Queue<TreeNode> q = new LinkedList<TreeNode>();
            q.add(root);
            while(q.size()>0){
                int size = q.size();
                List<Integer> l = new ArrayList<Integer>();
                for(int i=0;i<size;i++){
                    TreeNode node = q.poll();
                    if(toRight==1)
                        l.add(node.val);
                    else
                        l.add(0,node.val);
                    if(node.left!=null) q.add(node.left);
                    if(node.right!=null) q.add(node.right);
                }
                toRight = 1-toRight;
                result.add(l);
            }
            return result;
        }
    }

  • 0
    T

    This could be much more clear: LinkedList (and Deque interface) has addFirst and addLast methods; and toRight could be a boolean to prevent confusion between 1 and l. But in general, just don't use l as variable name.


Log in to reply
 

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