Java, simple recursion with accumulator, 8 lines, beats 87.5%

  • 3
     public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> levels = new ArrayList<>();
        levelOrder(root, 0, levels);
        return levels;
    public void levelOrder(TreeNode node, int level, List<List<Integer>> levels) {
        if (node == null) return;
        if (levels.size() == level) levels.add(new ArrayList<>());
        levelOrder(node.left, level, levels);
        levelOrder(node.right, level, levels);

Log in to reply

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