【leetcode 111】 二叉树的最小深度

记住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))
posted @ 2020-11-25 11:39  WangSJiNa  阅读(33)  评论(0)    收藏  举报