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

    给定一个二叉树,找出其最小深度。

    最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

    说明:叶子节点是指没有子节点的节点。

    示例 1:


    输入:root = [3,9,20,null,null,15,7]
    输出:2
    示例 2:

    输入:root = [2,null,3,null,4,null,5,null,6]
    输出:5

    解法一:递归求解  目前这个做法简练,有时候我们可以对条件的建立进行归纳

    取当前节点的左右子树的最小值加上当前节点,由于左右子树可能为空,则最小值的非空子树加一

    public:
        int minDepth(TreeNode* root) {
            if(!root)   return 0;
            if(!root->left || !root->right)    
                return max(minDepth(root->left)+1, minDepth(root->right)+1);
            return min(minDepth(root->left)+1, minDepth(root->right)+1);
        }

    贴一个国际站大神,经人指点,这个大神写的代码写的代码一般不错

    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        int L = minDepth(root.left), R = minDepth(root.right);
        return L<R && L>0 || R<1 ? 1+L : 1+R;
    }

    解法二:宽度优先搜索

    思路:从根节点开始,遍历每一层,如果节点没有左右子树说明遇到叶子节点则找到树的最小高度,如果是非叶子节点则加入队列,继续对下一层遍历

    复杂度分析

    public int minDepth(TreeNode root) {
            if (root == null)
                return 0;
            Queue<TreeNode> queue = new LinkedList<>();
            int minlen = 0;
            queue.add(root);
            while (!queue.isEmpty()) {
                minlen++;
                int size = queue.size();
                while (size > 0) {
                    TreeNode temp = queue.poll();
                    if (temp.left != null)
                        queue.add(temp.left);
                    if (temp.right != null)
                        queue.add(temp.right);
                    if (temp.left == null && temp.right == null)
                        return minlen;
                    size--;
                }
    
            }
            return minlen;
        }

    时间复杂度:O(N)O(N),其中 NN 是树的节点数。对每个节点访问一次。

    空间复杂度:O(N)O(N),其中 NN 是树的节点数。空间复杂度主要取决于队列的开销,队列中的元素个数不会超过树的节点数。

     这个题更让我关注,数据本身的结构和定义,比如叶子结点的定义,怎么用代码的语言描述叶子结点

  • 相关阅读:
    微信小程序 scroll-view switch checkbox
    微信小程序 全选和取消全选
    微信小程序 for循环添加样式1
    微信小程序 类似弹出菜单特效,从右向左滑出
    微信小程序 for循环 wx:for和wx:if wx:elif嵌套着使用
    微信小程序 输入框限制字数
    微信小程序 从本地相册选择图片或使用相机拍照chooseImage()和预览图片previewImage()
    安卓开发感言
    安卓-singleTask
    安卓-什么是FrameLayout
  • 原文地址:https://www.cnblogs.com/xiaoming521/p/14870812.html
Copyright © 2011-2022 走看看