题解 | #牛群左侧视图#
牛群左侧视图
https://www.nowcoder.com/practice/1eba2dd947484c078e6359ccd90aa7b1
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) { if(root == null) return new int[]{}; //层序遍历 Queue<TreeNode> q = new LinkedList<>(); List<Integer> list = new ArrayList<>(); q.offer(root); //判断队列是否为空,结束条件 while(!q.isEmpty()){ //每层的数据大小 int size = q.size(); for(int i=0;i<size;i++){ TreeNode node = q.poll(); if(node.left != null) q.offer(node.left); if(node.right != null) q.offer(node.right); //每层的第一个元素最是最左元素 if(i == 0) list.add(node.val); } } //遍历封装结果集 int[] res = new int[list.size()]; for(int i=0;i<list.size();i++){ res[i] = list.get(i); } return res; } }