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

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务