题解 | #牛群的最短路径#

牛群的最短路径

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;
    }
}

全部评论

相关推荐

06-12 16:23
已编辑
小米_软件开发(准入职员工)
点赞 评论 收藏
分享
05-29 20:34
门头沟学院 C++
KarlAllen:得做好直接春招的准备。学历差的话,一是面试要求会比学历好的严格不少,二是就算面试通过了也会被排序。总之暑期和秋招对于学历差的就是及其不友好
无实习如何秋招上岸
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务