Easy to understand 1ms Java Solution - beats 97% runtime


  • 0
    K
    public class Solution {
        ArrayList<List<Integer>> list = new ArrayList<>();
        public List<List<Integer>> levelOrderBottom(TreeNode root) {
            add(root,0);
            ArrayList<List<Integer>> a = new ArrayList<>();
            int size = list.size() - 1;
            for(int i = 0;i <= size;i++)
                a.add(list.get(size - i));
            return (List)a;
        }
        private void add(TreeNode root, int k){
            if(root == null) return;
            if(list.size() < k + 1){
               list.add(new ArrayList<Integer>());
            }
            List<Integer> subList = list.get(k);
            subList.add(root.val);
            list.set(k,subList);
            add(root.left,k+1);
            add(root.right,k+1);
        }
    }
    

Log in to reply
 

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