题解 | #牛群仰视图#
牛群仰视图
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); } }