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));
        }
  • 相关阅读:
    VOA 转
    DataTable中动态的赋值 转
    哈希表 转
    利用Hook技术实现键盘监控 转
    sql 里的 order by 和 group by 的区别 转
    DES加密算法 转
    Windows的消息机制 转
    “赢在中国”点评人给80后年轻人的30个忠告 转
    ASCII码对照表 转
    以太网 转
  • 原文地址:https://www.cnblogs.com/zeroingToOne/p/7930633.html
Copyright © 2011-2022 走看看