【牛客题霸每日一题】NC15 求二叉树的层序遍历
用dfs求解
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * } */ public class Solution { /** * * @param root TreeNode类 * @return int整型ArrayList<ArrayList<>> */ public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) { // write code here ArrayList<ArrayList<Integer>> result = new ArrayList<>(); helper(root, result, 0); return result; } private void helper(TreeNode root, ArrayList<ArrayList<Integer>> result, int depth) { if (root == null) return; if (result.size() == depth) result.add(new ArrayList<>()); result.get(depth).add(root.val); helper(root.left, result, depth + 1); helper(root.right, result, depth + 1); } }