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));
        }
  • 相关阅读:
    断点调试
    内部类
    继承2
    继承
    构造函数
    方法
    二维数组
    HTML 一
    使用mySQL与数据库进行交互(一)
    使用mySQL与数据库进行交互(二)
  • 原文地址:https://www.cnblogs.com/zeroingToOne/p/7930633.html
Copyright © 2011-2022 走看看