Easy but slow java method


  • 0
    X
    public class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            if(root == null) {
                return result;
            }
            
            Queue<TreeNode> queue = new ArrayDeque<TreeNode>();
            queue.add(root);
            int level = 0;
            
            while (!queue.isEmpty()){
                
                int size = queue.size();
                List<Integer> list = new ArrayList<Integer>();
                for (int i = 0; i < size; i++) {
                    TreeNode node = queue.poll();
                    list.add(node.val);
                    if (node.left != null) {
                        queue.offer(node.left);
                    }
                    if (node.right != null) {
                        queue.offer(node.right);
                    }
                }
                if (level % 2 == 1) {
                    list = reverse(list);
                }
                level++;
                result.add(list);
            }
            return result;
        }
        public List<Integer> reverse(List<Integer> list) {
            if (list == null) {
                return null;
            }
            
            int start = 0;
            int end = list.size() - 1;
            while (start < end) {
                int tmp = list.get(start);
                list.set(start, list.get(end));
                list.set(end, tmp);
                start++;
                end--;
            }
            return list;
        }
    }

  • 0
    T

    If you're reversing you might as well call Collections.reverse.


Log in to reply
 

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