> 文章列表 > Leetcode.111 二叉树的最小深度

Leetcode.111 二叉树的最小深度

Leetcode.111 二叉树的最小深度

题目链接

Leetcode.111 二叉树的最小深度 easy

题目描述

给定一个二叉树,找出其最小深度。

最小深度是从 节点最近叶子节点最短路径上的节点数量

说明: 叶子节点是指没有子节点的节点。

示例 1:

Leetcode.111 二叉树的最小深度

输入:root = [3,9,20,null,null,15,7]
输出:2

示例 2:

输入:root = [2,null,3,null,4,null,5,null,6]
输出:5

提示:

  • 树中节点数的范围在 [0,105][0, 10^5][0,105]
  • −1000<=Node.val<=1000-1000 <= Node.val <= 10001000<=Node.val<=1000

解法:递归

我们要求的是 叶子结点根结点最短路径

我们设 lllrrr 分别是 当前结点 rootrootroot 的左子节点到根结点的最短路径长度当前结点 rootrootroot 的右子节点到根结点的最短路径长度

  • 如果 l==0l ==0l==0,返回 r+1r + 1r+1
  • 如果 r==0r == 0r==0,返回 l+1l + 1l+1
  • 否则返回 min{l,r}+1min\\{l , r \\} + 1min{l,r}+1

时间复杂度:O(n)O(n)O(n)

C++代码:

class Solution {
public:int minDepth(TreeNode* root) {if(root == nullptr) return 0;int l = minDepth(root->left);int r = minDepth(root->right);if(l == 0) return r + 1;else if(r == 0) return l + 1;return min(l , r) + 1;}
};

Python代码:


class Solution:def minDepth(self, root: Optional[TreeNode]) -> int:if root == None:return 0l = self.minDepth(root.left)r = self.minDepth(root.right)if l == 0:return r + 1elif r == 0:return l + 1else:return min(l , r) + 1