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

相关推荐

不愿透露姓名的神秘牛友
06-11 13:34
offe从四面八方来:我真的没时间陪你闹了
点赞 评论 收藏
分享
07-14 13:47
门头沟学院 Java
Lynn012:你评估好自己的位置了吗《顶尖应届》
投递小米集团等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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