题解 | #牛群仰视图# 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,并返回。
全部评论

相关推荐

溱元:前端每年固定死几次,看两集广告就复活了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务