zoukankan      html  css  js  c++  java
  • 111.Minimum Depth of Binary Tree

    # 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 root == None:
                return 0
            if root.left == None and root.right != None:
                return self.minDepth(root.right) + 1
            if root.left != None and root.right == None:
                return self.minDepth(root.left) + 1
            return min(self.minDepth(root.left), self.minDepth(root.right)) + 1

    Java 版:

    思路:
      • 需要返回的是叶子节点的最小深度,所以,必须要是 叶子节点的深度 才有效。
      • 当某节点的左右子树,有一边是空时,则返回另一边的深度结果,用 max 得到不为空的子树结果;
      • 当某节点的左右子树,都不为空时,则返回这两个结果中的最小值!

    class Solution {
        public int minDepth(TreeNode root) {
            if(root == null) return 0;
            int leftRes = minDepth(root.left) + 1;
            int rightRes = minDepth(root.right) + 1;
            if(root.left == null || root.right == null) return Math.max(leftRes, rightRes);
            return Math.min(leftRes, rightRes);
        }
    }
  • 相关阅读:
    Poj-1088-滑雪
    Poj-2250-Compromise
    CF
    KMP算法
    01背包
    NY 269 VF
    PHP--1+2+3……100=?
    PHP企业发放的奖金--if...elseif...
    2019年中级考试题(附答案)
    PHP的IF条件语句-- 输入一个数字进行判断等级
  • 原文地址:https://www.cnblogs.com/luo-c/p/12857327.html
Copyright © 2011-2022 走看看