题解 | #牛群的最短路径#
牛群的最短路径
https://www.nowcoder.com/practice/c07472106bfe430b8e2f55125d817358?tpId=354&tqId=10591753&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 {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
public int minDepth (TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 1;
}
if (root.left == null) {
return 1 + minDepth(root.right);
}
if (root.right == null) {
return 1 + minDepth(root.left);
}
return 1 + Math.min(minDepth(root.left), minDepth(root.right));
}
}
本题知识点分析:
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,和最深高度不同
本题使用编程语言: Java
如果您觉得本篇文章对您有帮助的话,可以点个赞支持一下,感谢~

查看3道真题和解析
智元机器人成长空间 174人发布