zoukankan      html  css  js  c++  java
  • Leetcode练习(Python):树类:第111题:二叉树的最小深度:给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

    题目:

    二叉树的最小深度:给定一个二叉树,找出其最小深度。  最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

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

    思路:

    递归求解,但要注意的是测试样例[1,2],因为1不能作为叶子节点所以结果是2,设计程序的时候要规避。

    程序:

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def minDepth(self, root: TreeNode) -> int:
            if not root:
                return 0
            if not root.left and not root.right:
                return 1
            return self.findDepth(root)
    
        def findDepth(self, node: TreeNode):
            left_depth = float("-inf")
            right_depth = float("-inf")
            if not node:
                return 0
            if not node.left and not node.right:
                return 1
            left_depth = max(self.findDepth(node.left), left_depth)
            right_depth = max(self.findDepth(node.right), right_depth)
            if left_depth == 0 and right_depth != 0:
                return right_depth + 1
            elif left_depth != 0 and right_depth == 0:
                return left_depth + 1
            elif left_depth != 0 and right_depth != 0:
                return min(left_depth, right_depth) + 1
    

      

  • 相关阅读:
    操作系统典型调度算法
    C++ volatile 关键字
    vue class绑定 组件
    yarn 基本用法
    vscode 插件安装以及首选项配置
    git 多人协作
    git Feature分支
    git Bug分支
    git 分支策略
    git 解决冲突
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12922403.html
Copyright © 2011-2022 走看看