题解 | #牛群仰视图#
牛群仰视图
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中,最后转成数组返回就是。