题解 | #牛群仰视图#
牛群仰视图
https://www.nowcoder.com/practice/0f37a18320c4466abf3a65819592e8be
- 题目考察的知识点
二叉树的中序遍历
- 题目解答方法的文字分析
这道题的本质就是将二叉树的叶子节点值从左到右保存到数组下。符合从左到右的遍历顺序就是中序遍历。直接中序遍历二叉树,遍历到叶子节点就将值保存到队列当中,由于队列先进先出的特点,可以有效保存值的顺序。
- 本题解析所用的编程语言
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整型一维数组
*/
Queue<Integer> queue = new LinkedList<>();
public int[] bottomView (TreeNode root) {
if(root ==null){
return new int[0];
}
dfs(root);
int[] ans = new int[queue.size()];
int p=0;
for(Integer i: queue){
ans[p++]= i;
}
return ans;
}
public void dfs(TreeNode root) {
if(root==null){
return;
}
dfs(root.left);
if(root.left==null&&root.right==null){
queue.offer(root.val);
}
dfs(root.right);
}
}