题解 | #牛群左侧视图#
牛群左侧视图
https://www.nowcoder.com/practice/1eba2dd947484c078e6359ccd90aa7b1
知识点
树,层序遍历
解题思路
层序遍历(用两个双端队列完成),将每一层的第一个元素保存到list集合中,最后将list集合通过stream流转换成数组输出。
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 Deque<TreeNode> outer = new LinkedList<>(); Deque<TreeNode> inner = new LinkedList<>(); if(root != null) outer.offerFirst(root); List<Integer> list = new ArrayList<>(); while (!outer.isEmpty()){ while(!outer.isEmpty()){ inner.offerFirst(outer.pollLast()); } list.add(inner.getLast().val); while(!inner.isEmpty()){ TreeNode treeNode = inner.pollLast(); if(treeNode.left != null) outer.offerFirst(treeNode.left); if(treeNode.right != null) outer.offerFirst(treeNode.right); } } return list.stream().mapToInt(Integer::intValue).toArray(); } }