【牛客题霸每日一题】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);
    }
}
#笔试题目##字节跳动#
全部评论

相关推荐

流浪的神仙:无恶意,算法一般好像都得9硕才能干算法太卷啦
点赞 评论 收藏
分享
frutiger:逆天,我家就安阳的,这hr咋能说3k的,你送外卖不比这工资高得多?还说大厂来的6k,打发叫花子的呢?这hr是怎么做到说昧良心的话的
找工作时遇到的神仙HR
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务