题解 | #牛群左侧视图#
牛群左侧视图
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];
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
List<Integer> list = new ArrayList<>();
while (!queue.isEmpty()){
int size = queue.size();
int i=0;
int start=-1;
boolean flag = true;
for (i=0;i<size;i++){
if(queue.peek().left != null)
queue.add(queue.peek().left);
if(queue.peek().right != null)
queue.add(queue.peek().right);
if(flag){
start = queue.peek().val;
flag = !flag;
}
queue.poll();
}
list.add(start);
}
return list.stream().mapToInt(Integer::intValue).toArray();
}
}
