• leetcode111:二叉树的最小深度 && 剑指offer55:二叉树的深度


    给定一个二叉树,找出其最小深度。

    最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

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

    示例:

    给定二叉树 [3,9,20,null,null,15,7],

    3
    /
    9 20
    /
    15 7
    返回它的最小深度  2.

    ==============Python=============

    # 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
            res = 10 ** 9
            if root.left:
                res = min(res, self.minDepth(root.left))
            if root.right:
                res = min(res, self.minDepth(root.right))
    
            return res + 1

    ==============Java==============

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int minDepth(TreeNode root) {
            if (root == null) {
                return 0;
            }
            if (root.left == null && root.right == null) {
                return 1;
            }
            int res = Integer.MAX_VALUE;
            if (root.left != null) {
                res = Math.min(minDepth(root.left), res);
            }
            if (root.right != null) {
                res = Math.min(minDepth(root.right), res);
            }
            return res + 1;
        }
    }

    输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。

    例如:

    给定二叉树 [3,9,20,null,null,15,7],

    3
    /
    9 20
    /
    15 7
    返回它的最大深度 3 。

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def maxDepth(self, root: TreeNode) -> int:
            if not root:
                return 0
            return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
  • 相关阅读:
    IOS开发mapkit学习笔记
    IOS的两种框架设计思想
    关于创建及使用多线程的几种方法
    Linux基础入门 之挑战:历史命令
    20172018网络攻防第三周
    20172018网络攻防第二周
    Linux基础入门实验楼挑战之数据提取
    iconfont字体图标的使用方法超简单!
    CSS中的绝对定位(absolute)误区
    获取对象属性的点方法和中括号法的区别
  • 原文地址:https://www.cnblogs.com/liushoudong/p/13539157.html
Copyright © 2020-2023  润新知