原题
https://leetcode.cn/problems/minimum-depth-of-binary-tree/description/
思路
递归
复杂度
时间:O(n)
空间:O(n)
Python代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
if root.left is None and root.right is None:
return 1
# 左右子树的最小深度
leftDepth, rightDepth = float("inf"), float("inf")
if root.left:
leftDepth = self.minDepth(root.left)
if root.right:
rightDepth = self.minDepth(root.right)
return min(leftDepth, rightDepth) + 1
Go代码
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func minDepth(root *TreeNode) int {
if root == nil {
return 0
}
if root.Left == nil && root.Right == nil {
return 1
}
// 子树的最小深度
leftDepth, rightDepth := math.MaxInt32, math.MaxInt32
if root.Left != nil {
leftDepth = minDepth(root.Left)
}
if root.Right != nil {
rightDepth = minDepth(root.Right)
}
return 1 + min(leftDepth, rightDepth)
}
1105

被折叠的 条评论
为什么被折叠?



