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

牛群的最短路径

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

一、知识点:

遍历、二叉树

二、文字分析:

使用递归的方式遍历二叉树,并计算每个节点的最短路径。具体步骤如下:

  1. 如果二叉树的根节点为空,直接返回0,表示最短路径为0。
  2. 如果二叉树的左子树为空,递归计算右子树的最短路径,将其值保存在变量rightDepth中,并返回rightDepth加1,表示当前节点及其子树的最短路径。
  3. 如果二叉树的右子树为空,递归计算左子树的最短路径,将其值保存在变量leftDepth中,并返回leftDepth加1,表示当前节点及其子树的最短路径。
  4. 如果二叉树的左右子树都不为空,分别递归计算左子树和右子树的最短路径,将其值保存在变量leftDepth和rightDepth中,然后返回leftDepth和rightDepth中的较小值加1,表示当前节点及其子树的最短路径。

时间复杂度:O(N)

在最坏情况下,我们需要遍历二叉树的所有节点一次,其中N是二叉树中的节点数量。因此,时间复杂度为O(N)。

空间复杂度:O(H)

在递归的过程中,系统需要使用递归函数的调用栈。在最坏情况下,二叉树是一个单链的结构,递归的深度等于二叉树的高度H。因此,空间复杂度为O(H)。

三、编程语言:

java

四、正确代码:

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 {

    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        if (root.left == null) {
            return minDepth(root.right) + 1;
        }

        if (root.right == null) {
            return minDepth(root.left) + 1;
        }

        int leftDepth = minDepth(root.left);
        int rightDepth = minDepth(root.right);

        return Math.min(leftDepth, rightDepth) + 1;
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务