zoukankan      html  css  js  c++  java
  • 111.二叉树的最小深度

    class TreeNode:
    def __init__(self, x):
    self.val = x
    self.left = None
    self.right = None

    root1 = TreeNode(1)
    root2 = TreeNode(2)
    root1.left = root2
    # 这道题也是递归的想法,遍历每个子树,跟上一题的方法一样
    class Solution:
    def minDepth(self, root: TreeNode) -> int:
    return self.dfs(root)
    def dfs(self,root):
    # 首先判断根节点是否为None
    if not root : return 0
    # 分别求出左子树和右子树的最小路径
    left = self.dfs(root.left)
    right = self.dfs(root.right)
    # 注意这里一定要加判断的原因
    # 是因为,当左节点或者右节点为空的时候不能算在路径里边
    if left == 0 and right != 0:
    return right + 1
    elif left != 0 and right == 0:
    return left + 1
    # 返回左子树和右子树中最小的路径,当然,还要加上根节点。
    return min(left,right) + 1
    a = Solution()
    print(a.minDepth(root1))
  • 相关阅读:
    c++ *.h和*.cpp在编译中的作用
    test
    DOM Tree
    SecureCRT
    趣味盒1
    数据结构笔试:前缀表达式|后缀表达式
    Shell 文件包含
    Shell 输入/输出重定向
    Shell 函数
    Shell 流程控制
  • 原文地址:https://www.cnblogs.com/cong12586/p/13137847.html
Copyright © 2011-2022 走看看