题解 | #牛群的最短路径#
牛群的最短路径
https://www.nowcoder.com/practice/c07472106bfe430b8e2f55125d817358
题目考察的知识点
二叉树深度优先遍历
题目解答方法的文字分析
根据题意,只有当节点为null或者遍历到叶子节点的时候才会return。求的是最短的叶子节点距离,所以对于非叶子节点的探索都是+1后继续探索。所以分情况对应了有一个子树和两个子树都存在的情况,记得最后取min得到最短的从根到叶子的路径长度即可。
本题解析所用的编程语言
使用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整型
*/
public int minDepth (TreeNode root) {
// write code here
if(root==null) return 0;
if(root.left==null&&root.right!=null) return minDepth(root.right)+1;
if(root.left!=null&&root.right==null) return minDepth(root.left)+1;
return 1+Math.min(minDepth(root.left),minDepth(root.right));
}
}
查看16道真题和解析
