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

    这题需要考虑什么是最小深度,根节点到最近叶子节点的距离,为了防止一个子树为null的情况干扰后续的 Math.min(dfsMinDepth(root.left), dfsMinDepth(root.right))运算,将

    if (root == null) {
                // 例如 一个节点,左子树是null,右子树还有东西,左子树就会
                // return最大整数这样不影响计算最小depth
                return Integer.MAX_VALUE;
            }

    当然我看的答案

    import tree.TreeNode;
    
    public class MinDepth {
        /**
         * @param root: The root of binary tree
         * @return: An integer
         *
         * 155. 二叉树的最小深度
         * 给定一个二叉树,找出其最小深度。
         *
         * 二叉树的最小深度为根节点到最近叶子节点的距离。
         * 样例
         * 给出一棵如下的二叉树:
         *
         *         1
         *
         *      /     
         *
         *    2       3
         *
         *           /    
         */
    
        /**
         * 同二叉树的最大深度不同
         * 如果是求最大深度,就两种情况
         * root==null, return 0
         * root !=null, return 1+Math.max(root.left, root.right);
         * 二叉树的最小深度
         * 需要设立递归的辅助函数,分三种情况
         * root = null, return Integer.MAX_VALUE
         * root.left==null && root.right==null, return 1
         * return 1 + Math.min(left, right)
         */
        public int minDepth(TreeNode root) {
            if (root == null) {
                return 0;
            }
            int result = dfsMinDepth(root);
            return result == Integer.MAX_VALUE ? 0 : result;
        }
    
        public int dfsMinDepth(TreeNode root) {
            // write your code here
            if (root == null) {
                // 例如 一个节点,左子树是null,右子树还有东西,左子树就会
                // return最大整数这样不影响计算最小depth
                return Integer.MAX_VALUE;
            }
            if (root.left == null && root.right == null) {
                return 1;
            }
            return 1 + Math.min(dfsMinDepth(root.left), dfsMinDepth(root.right));
        }
    }
  • 相关阅读:
    面向对象
    6.jQuery基础_试题
    5.JavaScript操作BOM、DOM对象_试题
    css疑问
    JAVA学习笔记_五JAVA开发中的WEB前端技术
    java学习笔记_mysql随堂考试_错题
    java学习笔记④MySql数据库--03/04 DQL查询
    java学习笔记④MySql数据库--01/02 database table 数据的增删改
    java学习笔记③JAVA核心API编程-01集合框架和泛型
    java学习笔记②JAVA面向对象
  • 原文地址:https://www.cnblogs.com/wei1/p/9582052.html
Copyright © 2011-2022 走看看