Easy Java recursive solution - 2ms


  • 4
    H
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if(root == null) return res;
        return levelOrder(root, 0, res);
    }
    
    private List<List<Integer>> levelOrder(TreeNode root, int level, List<List<Integer>> res) {
        if(res.size() <= level) res.add(level, new ArrayList<Integer>());
        res.get(level).add(root.val);
        if (root.left != null) levelOrder(root.left, level+1, res);
        if (root.right != null) levelOrder(root.right, level+1, res);
        return res;
    }

Log in to reply
 

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