题解 | #牛群的最短路径#
牛群的最短路径
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) {
if(root == null) return 0;
//使用队列,进行层序遍历
Queue<TreeNode> q = new LinkedList<>();
//定义一个变量用于记录高度
int depth = 0;
q.offer(root);
while(!q.isEmpty()){
int size = q.size();
//每次遍历完一层就dapth+1;
for(int i=0;i<size;i++){
TreeNode node = q.poll();
if(node.left != null) q.offer(node.left);
if(node.right != null) q.offer(node.right);
//当节点没有子节点的时候,则说明该层是最矮层
if(node.left == null && node.right == null) return depth+1;
}
depth ++;
}
return depth;
}
}

