Iterative Java solution with queue used


  • 0
    H
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<TreeNode> queue = new LinkedList<>();
        List<Integer> tempList = new ArrayList<>();
        
        int currLevel = 1;
        int nxtLevel = 0;
        
        if (root != null) 
            queue.add(root);
            
        while (!queue.isEmpty()) {
            TreeNode node = queue.remove();
            tempList.add(node.val);
            currLevel--;
            
            if (node.left != null) {
                queue.add(node.left);
                nxtLevel++;
            }
            if (node.right != null) {
                queue.add(node.right);
                nxtLevel++;
            }
            
            if (currLevel == 0) {
                result.add(tempList);
                currLevel = nxtLevel;
                nxtLevel = 0;
                tempList = new ArrayList<>();
            }
        }
        
        return result;
        
    }

Log in to reply
 

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