Java solution with two queues


  • 0
    R
    public class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> solution = new ArrayList<> ();
            if (root == null) return solution;
            
            Queue<TreeNode> q = new LinkedList<>(); // To track nodes
            Queue<Integer> level = new LinkedList<>(); // To track level of the node added
            
            q.add(root); // Add the rootnode in the queue
            level.add(0); // All Level of root node (0)
            
            while (!q.isEmpty()) {
                TreeNode currNode = q.remove();
                int currLevel = level.remove();
                try {
                    solution.get(currLevel); // get throws an exception if currLevel does not exist
                } catch(Exception e) {
                    solution.add(currLevel,new ArrayList<Integer>()); // Create a new arraylist for the current Level
                }
                
                solution.get(currLevel).add(currNode.val); // Add the value of node to the current level list
                
                // Update both the queues
                if (currNode.left != null) {
                    level.add(currLevel + 1);
                    q.add(currNode.left);
                }
                
                if (currNode.right != null) {
                    level.add(currLevel + 1);
                    q.add(currNode.right);
                }
            }
            
            return solution;
        }
    }

Log in to reply
 

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