Simple 3ms Java solution.


  • 0
    J
    public class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            
            List<List<Integer>> resList = new ArrayList<List<Integer>>();
            
            if(root==null) return resList;
            
            Deque<TreeNode> bfs = new ArrayDeque<TreeNode>();
            bfs.add(root);
            int count=1;
            
            while(!bfs.isEmpty())
            {
                List<Integer> levelNodeValues = new ArrayList<Integer>();
                int tempCount=0,nextLevelCount=0;
                
                while(tempCount<count)
                {
                    TreeNode tempNode =bfs.poll();
                    levelNodeValues.add(tempNode.val);
                    
                    if(tempNode.left!=null){
                        nextLevelCount++;
                        bfs.add(tempNode.left);
                    }
                    if(tempNode.right!=null){
                        nextLevelCount++;
                        bfs.add(tempNode.right);
                    }
                    tempCount++;
                }
                
                resList.add(levelNodeValues);
                count=nextLevelCount;
                
            }
            
            return resList;
        }
    }
    

Log in to reply
 

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