题解 | #牛群仰视图#
牛群仰视图
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 // 其实就是叶子节点 if (root == null) { return new int[]{}; } int i = getCount(root); System.out.print(i); int[] res = new int[i]; i = 0; TreeNode cur = root; TreeNode mostRight = null; while (cur != null) { mostRight = cur.left; if (mostRight != null) { while (mostRight.right != null && mostRight.right != cur) { mostRight = mostRight.right; } if(mostRight.right == null) { // 第一次到达 // res[i++] = mostRight.val; mostRight.right = cur; cur = cur.left; continue; } else { // 第二次到达 if (mostRight.left == null) { res[i++] = mostRight.val; } mostRight.right = null; } } cur = cur.right; } cur = root; while (cur.right != null) { cur = cur.right; } res[i++] = cur.val; return res; } //1, 2, 3, 4, #, #, 5} 4,5 public int getCount(TreeNode root) { if (root == null) return 0; if (root.left == null && root.right == null) return 1; return getCount(root.left) + getCount(root.right); } }#java##morris遍历#