My solution using HashMap


  • 0
    N
    public class Solution {
        HashMap<Integer,List<Integer>> byLevel = new HashMap<Integer,List<Integer>>();
        public List<List<Integer>> levelOrder(TreeNode root) {
            if(root==null) return new ArrayList<List<Integer>>();
            Integer level = 0;
            createList(root,0);
            List<List<Integer>> finalList = new ArrayList<List<Integer>>();
            for(Map.Entry<Integer, List<Integer>> entry : byLevel.entrySet()){
                finalList.add(entry.getValue());
            }
            return finalList;
        }
        private void createList(TreeNode root,Integer level){
            if(root==null) return;
            if(byLevel.containsKey(level)){
                byLevel.get(level).add(root.val);
            }
            else{
                List<Integer> l = new ArrayList<Integer>();
                l.add(root.val);
                byLevel.put(level,l);
            }
            if(root.left!=null){
                createList(root.left,level+1);
            }
            if(root.right!=null){
                createList(root.right,level+1);
            }
            if(root.left==null && root.right==null){
                return;
            }
        }
    }

Log in to reply
 

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