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));
        }
  • 相关阅读:
    2014-11-27-0047-Java
    js去除数组中重复值
    一个数据表更新另外一个数据表(SQL)
    《js12种设计模式》
    《可编辑td》
    《JS 隔行换色》
    用Autohotkey让Kitty命令行变得更好用
    View epub and mobi File on Linux
    DrJava试用笔记
    Notes about BSD
  • 原文地址:https://www.cnblogs.com/zeroingToOne/p/7930633.html
Copyright © 2011-2022 走看看