Easy Java Solution


  • 0
    K
    public class Solution {
        ArrayList<List<Integer>> list = new ArrayList<>();
        public List<List<Integer>> levelOrder(TreeNode root) {
            add(root, 0);
            return (List)list;
        }
        private void add(TreeNode root,int k){
            if(root != null){
                List<Integer> subList;
                if(list.size() < k + 1)
                   subList = new ArrayList<>();
                else subList = list.remove(k);
                subList.add(root.val);
                list.ensureCapacity(k+1);
                list.add(k,subList);
                add(root.left,k+1);
                add(root.right,k+1);
            }
            else return;
        }
    }
    

Log in to reply
 

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