Java Solution that beats 90%


  • 0
    E
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>>arrlist=new ArrayList<List<Integer>>();
            populateList(root,arrlist,0);
            return arrlist;
        }
        public void populateList(TreeNode root, List<List<Integer>>arrlist, int level){
            if(root==null){
                return;
            }
            if(arrlist.size()-1<level){
                List<Integer>list=new ArrayList<Integer>();
                list.add(root.val);
                arrlist.add(list);
            }
            else{
                arrlist.get(level).add(root.val);
            }
            populateList(root.left,arrlist,level+1);
            populateList(root.right,arrlist,level+1);
        }
    }
    

Log in to reply
 

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