题解 | #牛群左侧视图#

牛群左侧视图

https://www.nowcoder.com/practice/1eba2dd947484c078e6359ccd90aa7b1

题目考察的知识点是:

本题主要考察二叉树的遍历。

题目解答方法的文字分析:

将集合循环,记录每一层的第一个值,将这个记录返回即可得到结果。

本题解析所用的编程语言:

java语言。

完整且正确的编程代码:

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param root TreeNode类
     * @return int整型一维数组
     */
    public int[] leftSideView (TreeNode root) {
        // write code here
        if (root == null)   {
            return new int[0];
        }
        ArrayList<ArrayList<Integer>> arrayLists = level(root);
        int[] arr = new int[arrayLists.size()];
        int count = 0;
        for (int i = 0; i < arrayLists.size(); i++) {
            arr[count++] = arrayLists.get(i).get(0);
        }
        return arr;
    }


    public ArrayList<ArrayList<Integer>> level(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            ArrayList<Integer> arr = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode q = queue.remove();
                arr.add(q.val);
                if (q.left != null) {
                    queue.add(q.left);
                }
                if (q.right != null) {
                    queue.add(q.right);
                }
            }
            arrayLists.add(arr);
        }
        return arrayLists;
    }
}

全部评论

相关推荐

2024-12-29 19:48
河北科技大学 Java
我真的会练有氧:1.如果没有实习经验,项目一个太少了 2.项目的需求描述不要写成用xxx实现了xxx。写明具体的需求功能就可以,除非是你想特别突出让面试官问的问题 3.证书就一个4级没必要摆上去,摆上去显得你就只有一个4级 4.技术栈太少了,且比较简略,可以加点分布式,常用的微服务组件,架构设计等等信息 个人意见,不喜勿喷
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务