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

    111. 二叉树的最小深度

    https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/description/

    package com.test;
    
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * @Author stono
     * @Date 2018/9/3 上午8:06
     */
    public class Lesson111 {
        public static void main(String[] args) {
            TreeNode t1 = new TreeNode(1);
            TreeNode t2L = new TreeNode(2);
            TreeNode t2R = new TreeNode(2);
            TreeNode t3_1 = new TreeNode(3);
            TreeNode t3_2 = new TreeNode(4);
            TreeNode t3_3 = new TreeNode(4);
            TreeNode t3_4 = new TreeNode(3);
            t1.left = t2L;
            t1.right = t2R;
            t2L.left = t3_1;
            t2L.right = t3_2;
            t2R.left = t3_3;
            t2R.right = t3_4;
    
            int i = minDepth(t1);
            System.out.println(i);
    
        }
    
        public static int minDepth(TreeNode root) {
            if (root == null) {
                return 0;
            }
            List<Integer> list = new ArrayList<>(8);
            minDepth(1, root, list);
            int min = list.get(0);
            for (int i = 1; i < list.size(); i++) {
                if (list.get(i) < min) {
                    min = list.get(i);
                }
            }
            return min;
        }
    
        /**
         * 把中间的结果都进行缓存
         * @param i
         * @param root
         * @param list
         */
        private static void minDepth(int i, TreeNode root, List<Integer> list) {
            // 叶子节点的情况
            if (root.left == null && root.right == null) {
                list.add(i);
            } else {
                if (root.left != null) {
                    minDepth(i + 1, root.left, list);
                }
                if (root.right != null) {
                    minDepth(i + 1, root.right, list);
                }
            }
        }
    }
  • 相关阅读:
    springboot添加邮件发送及压缩功能
    springboot添加多数据源连接池并配置Mybatis
    SpringMVC+Mybatis初尝试
    个人课程总结
    第十六周学习总结
    第十五周学习总结
    第二阶段冲刺九
    第二阶段冲刺八
    第二阶段冲刺七
    搜狗拼音输入法使用评价
  • 原文地址:https://www.cnblogs.com/stono/p/9576913.html
Copyright © 2011-2022 走看看