题解 | #牛群仰视图#

牛群仰视图

https://www.nowcoder.com/practice/0f37a18320c4466abf3a65819592e8be?tpId=354&tqId=10591721&ru=/exam/oj&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj

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 {
    List<Integer> list = new ArrayList<>();
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param root TreeNode类
     * @return int整型一维数组
     */
    public int[] bottomView (TreeNode root) {
        // write code here
        fun(root);
        return list.stream().mapToInt(Integer::intValue).toArray();
    }
 
    public void fun(TreeNode root){
        if(root == null) return;
        if(root.left == null && root.right == null){
            list.add(root.val);
        }
        fun(root.left);
        fun(root.right);
    }

}

知识点:

树,先序遍历

解题思路:

理解这道题目的意思,只要有左右树节点就会遮挡父节点,因此其实就是需要我们找到树的全部叶子节点。

就只需要先序遍历整棵树,找到左右子节点为空的节点放到list中,最后转成数组返回就是。

全部评论

相关推荐

陈逸轩1205:才105 哥们在养生呢
点赞 评论 收藏
分享
07-07 14:30
复旦大学 Java
遇到这种人我也不知道说啥了
无能的丈夫:但我觉得这个hr语气没什么问题啊(没有恶意
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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