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

牛群的最短路径

https://www.nowcoder.com/practice/c07472106bfe430b8e2f55125d817358

  1. 题目考察的知识点

二叉树的遍历,层次遍历

  1. 题目解答方法的文字分析

本题可以用二叉树的广度优先搜索来解决。因为二叉树的层数就是二叉树的最大深度。而牛群的最短路径就是看二叉树哪一层先出现叶子节点。遍历每一层时,搜索叶子节点,当搜索到时,返回层数,层数便是最短路径长度。

  1. 本题解析所用的编程语言

java

  1. 完整且正确的编程代码
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) {
        int depth = 0;
        if(root==null){
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int count = queue.size();
            depth++;
            while (count-- > 0) {
                TreeNode node = queue.poll();
                if(node.left==null&&node.right==null){
                    return depth;
                }
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }

        }
        return depth;
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务