0 题目描述
leetcode原题链接:111. 二叉树的最小深度
1 递归解法
叶子节点的定义是左孩子和右孩子都为 null 时叫做叶子节点。
当 root 节点为 null 时,返回 0。
当 root 节点左右孩子都为空时,返回 1。
当 root 节点左右孩子有一个为空时,返回不为空的孩子节点的深度。
当 root 节点左右孩子都不为空时,返回左右孩子较小深度的节点值。
# 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: TreeNode) -> int:
if not root: return 0
leftDepth = self.minDepth(root.left)
rightDepth = self.minDepth(root.right)
if not root.left or not root.right:
return leftDepth + rightDepth + 1
return 1 + min(leftDepth,rightDepth)
复杂度分析:
时间复杂度:
O
(
N
)
O(N)
O(N),其中 N 是树的节点数。对每个节点访问一次。
空间复杂度:
O
(
H
)
O(H)
O(H),其中 H 是树的高度。空间复杂度主要取决于递归时栈空间的开销,最坏情况下,树呈现链状,空间复杂度为
O
(
N
)
O(N)
O(N)。平均情况下树的高度与节点数的对数正相关,空间复杂度为
O
(
log
N
)
O(\log N)
O(logN)。