题解 | #牛群的最短路径#
牛群的最短路径
https://www.nowcoder.com/practice/c07472106bfe430b8e2f55125d817358
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 minDepth (TreeNode root) { // write code here if (root == null) { return 0; } ArrayList<Integer> arrayList = new ArrayList<>(); int count = 0; Depth(root, arrayList, count); int min = 1000; for (int i = 0; i < arrayList.size(); i++) { if (arrayList.get(i) < min) min = arrayList.get(i); } return min + 1; } public void Depth (TreeNode root, ArrayList<Integer> arrayList, int count) { if (root == null) { return; } if (root.left == null && root.right == null) { arrayList.add(count); return; } count++; Depth(root.left, arrayList, count); Depth(root.right, arrayList, count); } }
本题知识点分析:
1.二叉树搜索树
2.深度优先搜索
本题解题思路分析:
1.分类讨论 如果root==null,直接返回0
2.如果root.left和root.right==null,说明只有一个root根节点,返回1
3.如果是left或者right==null,那么另外一个必然不为null,return 1+minDepth(root.另外一个不为null的节点)
4.如果都不为Null,那么 return 1 + Math.min(minDepth(root.left), minDepth(root.right));因为是找最短路径因此要Math.min,和最深高度不同