Java solution with queue


  • 0
    I
    public class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> lists = new ArrayList<>();
            TreeNode split = new TreeNode(-1);
            Queue<TreeNode> queue = new LinkedList<>();
            List<Integer> list = new ArrayList<>();
            queue.offer(root);
            queue.offer(split);
            boolean lastIsSplit = false;
            while(queue.peek() != null) {
                TreeNode node = queue.poll();
                if(node == split) {
                    if(lastIsSplit == true) break;
                    lists.add(new ArrayList(list));
                    list.clear();
                    queue.offer(split);
                    lastIsSplit = true;
                } else {
                    list.add(node.val);
                    if(node.left != null) queue.offer(node.left);
                    if(node.right != null) queue.offer(node.right);
                    lastIsSplit = false;
                }
            }
            return lists;
        }
    }
    

  • 0
    P

    hey so how come you need to do lists.add(new ArrayList(list)); instead of just lists.add(list)); ? didnt we declare list as an arraylist?


Log in to reply
 

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