1 ms Java, simple ArrayList + Recursion


  • 0
    J
    private static void collateByLevel(TreeNode node, int level, List<List<Integer>> levels) {
    if (node == null)  return;
    
    if (levels.size() < level + 1)  levels.add(new ArrayList<>());
    
    List<Integer> thisLevel = levels.get(level);
    thisLevel.add(node.val);
    collateByLevel(node.left, level + 1, levels);
    collateByLevel(node.right, level + 1, levels);
    }
    
    public List<List<Integer>> levelOrder(TreeNode root) {    
      List<List<Integer>> levels = new ArrayList<>();
      collateByLevel(root,0,levels);
      return levels;
    }

Log in to reply
 

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