题解 | #牛群的最短路径# java
牛群的最短路径
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整型
*/
int minDepth = Integer.MAX_VALUE;
public void dfs(TreeNode root, int depth) {
if (root.left == null && root.right == null) {
minDepth = Math.min(minDepth, depth);
return;
}
if (root.left != null) {
dfs(root.left, depth + 1);
}
if (root.right != null) {
dfs(root.right, depth + 1);
}
}
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
dfs(root, 1);
return minDepth;
}
}
代码使用的编程语言是Java。
该题考察的知识点是二叉树和深度优先搜索(DFS)。
代码的文字解释如下:
首先定义了一个TreeNode类,其中包含一个整型变量val,以及左右子节点left和right。
然后定义了一个Solution类,其中包含一个整型变量minDepth,用来保存最小深度的结果。
在Solution类中,定义了一个私有方法dfs,用于进行深度优先搜索。
在dfs方法中,首先判断当前节点是否为叶子节点(即没有左子节点和右子节点)。如果是叶子节点,则比较当前深度depth和minDepth的值,并将较小的值更新给minDepth。
然后,递归调用dfs方法处理左子树和右子树。
在递归调用前,将深度depth加1传递给下一层递归。
最后,在Solution类中定义了一个公共方法minDepth,接收一个树的根节点root作为参数,并返回二叉树的最小深度。
在minDepth方法中,首先判断根节点是否为空,如果为空则直接返回0。
然后,调用dfs方法进行深度优先搜索。
最后,返回计算得到的最小深度minDepth作为结果。

