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

    Given a binary tree, find its minimum depth.

    The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

    题意:求给定二叉树的最小深度

    思路1:层次遍历,找到最近的叶子结点就返回层数。代码如下:

    public int minDepth(TreeNode root) {
            if (root == null)
                return 0;
            int count = 1, size;
            Queue<TreeNode> q = new LinkedList<>();
            q.add(root);
            while (!q.isEmpty()) {
                size = q.size();
                for (int i = 0; i < size; i++) {
                    TreeNode t = q.poll();
                    if (t.left == null && t.right == null)
                        return count;
                    if (t.left != null)
                        q.add(t.left);
                    if (t.right != null)
                        q.add(t.right);
                }
                count++;
            }
            return 0;
        }

    思路2:利用递归

    public int minDepth(TreeNode root) {
            if (root == null)
                return 0;
            if (root.left == null && root.right == null) // 如果当前结点的左右子树都为空,则当前结点为叶子结点
                return 1;
            if (root.left == null)// 左子树为空,右子树非空
                return 1 + minDepth(root.right);
            else if (root.right == null)// 左子树非空,右子树为空
                return 1 + minDepth(root.left);
            else // 左右子树都非空
                return 1 + Math.min(minDepth(root.left), minDepth(root.right));
        }
  • 相关阅读:
    Docker容器案例:应用 Mysql
    rpm 命令参数使用详解
    MySQL中的两种临时表
    Yum本地Rpm库设置
    编程学习 博客
    yum -------包安装库
    Linux 基础 —— RPM
    在CentOS上编译安装PostgreSQL
    Linux上安装JDK环境变量配置
    yum_rpm(利用dvd建立本地yum库)
  • 原文地址:https://www.cnblogs.com/zeroingToOne/p/7930633.html
Copyright © 2011-2022 走看看