Recursive Version in Java


  • 1
    Y
    class Solution {
    
    public List<List<Integer>> levelOrder(TreeNode root) {
            Queue<TreeNode> queue = new LinkedList<>();
            List<List<Integer>> outerList = new ArrayList<>();
            queue.add(root);
            return level(queue, outerList);
        }
    
        private List<List<Integer>> level(Queue<TreeNode> queue, List<List<Integer>> outerList) {
            Queue<TreeNode> newQueue = new LinkedList<>();
            List<Integer> aList = new ArrayList<>();
            while (!queue.isEmpty()) {
                TreeNode thisNode = queue.poll();
                if (thisNode == null) continue;
                aList.add(thisNode.val);
                newQueue.add(thisNode.left);
                newQueue.add(thisNode.right);
            }
            if (aList.isEmpty())
                return outerList;
            outerList.add(aList);
            return level(newQueue, outerList);
        }
    }
    

Log in to reply
 

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