牛客题霸NC15 求二叉树的层序遍历题解
求二叉树的层序遍历
https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3?tpId=117&&tqId=34936&rp=1&ru=/ta/job-code-high&qru=/ta/job-code-high/question-ranking
知识点:树   bfs
难度:中等
考过的企业: 快手,字节跳动,好未来,美团,涂鸦移动,作业帮,叠纸游戏,远景能源,猿辅导,有赞,网易,小米,滴滴,百度,FreeWheel,OPPO,最右
考过的职位: 研发工程师(包括java工程师,c++工程师等),客户端工程师,前端工程师,算法工程师,测试工程师
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);
    }
} 
查看7道真题和解析
