1 ms Java Solution


  • 0
    C
    public class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> set = new ArrayList<List<Integer>>();
            if(root == null) return set;
            List<Integer> tmp = new ArrayList<Integer>();
            boolean leftToRight = true;
            List<TreeNode> queue = new  ArrayList<>();
            queue.add(root);
            int itr = 0;
            TreeNode lastOne = root;
            while(itr != queue.size()) {
                TreeNode node = queue.get(itr);
                tmp.add(node.val);
                if(node.left != null) queue.add(node.left);
                if(node.right != null) queue.add(node.right);
                if(lastOne == node) {
                	if(leftToRight) {
                		List<Integer> l = new ArrayList<Integer>(tmp);
                		leftToRight = false;
                        set.add(l);
                	}
                	else {
                		List<Integer> l = new ArrayList<>();
                		for(int i = tmp.size() - 1; i >= 0; i--) l.add(tmp.get(i));     		
                		leftToRight = true;
                        set.add(l);
                	}
                	
                    tmp = new ArrayList<Integer>();
                    lastOne = queue.get(queue.size()-1);
                }
                itr++;
            }
            return set;
        }
    }

Log in to reply
 

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