zoukankan      html  css  js  c++  java
  • 二叉树的最大/小/平衡 深度 depth of binary tree

    [抄题]:

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

    二叉树的深度为根节点到最远叶子节点的距离。

    [思维问题]:

    [一句话思路]:

    分合法的定义

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    求最小距离时,注意左边或右边没有数的情况。

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

    [总结]:

    [复杂度]:Time complexity: O(n) Space complexity: O(n)

    [英文数据结构,为什么不用别的数据结构]:

    只有算法,没有数据结构

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

    public class Solution {
        /**
         * @param root: The root of binary tree.
         * @return: An integer.
         */
        public int maxDepth(TreeNode root) {
            if (root == null) {
                return 0;
            }
            
            int left = maxDepth(root.left);
            int right = maxDepth(root.right);
            
            int max = Math.max(left,right);
            return max + 1;
        }
    }
    View Code
    public class Solution {
        /**
         * @param root: The root of binary tree.
         * @return: An integer.
         */
        public int minDepth(TreeNode root) {
            if (root == null) {
                return 0;
            }
            
            int left = minDepth(root.left);
            int right = minDepth(root.right);
            int result;
            int min = Math.min(left,right);
            
            if (left == 0 || right == 0) {
                result = left + right + 1;
            }
            else {
                result = min + 1;
            }
            return result;
        }
    }
    View Code
  • 相关阅读:
    二维数组转换
    二维数组转换
    二分法原理
    二维数组举例
    二分法原理
    二维数组举例
    二分法原理
    二分法原理
    linux中BIND服务程序安全的加密传输TSIG机制
    linux系统中部署DNS从服务器
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8371945.html
Copyright © 2011-2022 走看看