記住4個遞歸結束的判斷條件:
葉子節點的定義是左孩子和右孩子都爲 null 時叫做葉子節點
當 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
if not root.left and not root.right: return 1
if not root.left: return 1+self.minDepth(root.right)
if not root.right: return 1+self.minDepth(root.left)
return 1+ min(self.minDepth(root.left),self.minDepth(root.right))