题解 | #牛群仰视图# java
牛群仰视图
https://www.nowcoder.com/practice/0f37a18320c4466abf3a65819592e8be
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[] bottomView (TreeNode root) {
// write code here
List<Integer> re = new ArrayList<>();
if (root == null) {
return new int[0];
}
Stack<TreeNode> stk = new Stack<>();
stk.push(root);
TreeNode cur;
while (!stk.empty()) {
cur = stk.pop();
if (cur.left == null && cur.right == null) {
re.add(cur.val);
continue;
}
if (cur.right != null) {
stk.push(cur.right);
}
if (cur.left != null) {
stk.push(cur.left);
}
}
int[] result = new int[re.size()];
for (int i = 0; i < re.size(); i++) {
result[i] = re.get(i);
}
return result;
}
}
该代码使用的编程语言是Java
这道题考察的知识点是二叉树的遍历和栈的应用。
代码的文字解释如下:
bottomView方法接收一个TreeNode类型的参数root,返回一个存储着从二叉树底部视角看到的节点值的整型数组。- 首先创建一个空的整型向量
re,用于存储底部视角的节点值。 - 如果
root为空,则直接返回空数组。 - 创建一个栈
stk,将root压入栈中。 - 创建一个
cur指针,表示当前处理的节点。 - 当栈不为空时,进行以下循环:将栈顶的节点弹出并赋值给 cur。如果 cur 的左右子节点都为空,说明该节点是二叉树的底部节点,将其值加入到 re 中,并继续下一次循环。如果 cur 的右子节点不为空,将其压入栈中。如果 cur 的左子节点不为空,将其压入栈中。
- 循环结束后,将
re转换为整型数组result,并返回。

SHEIN希音公司福利 261人发布