Leetcode111. 二叉树的最小深度

思路1

四种情况:根节点空、左子树空、右子树空、左右子树非空

复杂度

时间复杂度: O(n)

空间复杂度: O(logn)

核心代码

cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int getDepth(TreeNode* root){
        //1.节点为空
        if(root==NULL) return 0;
        int leftDepth=getDepth(root->left);
        int rightDepth=getDepth(root->right);
        //2.左空
        if(root->left==NULL){
            return rightDepth+1;
        }
        //3.右空
        if(root->right==NULL){
            return leftDepth+1;
        }
        //4.左右非空
        return min(rightDepth,leftDepth)+1;
    }
    int minDepth(TreeNode* root) {
        return getDepth(root);
    }
};

//作者:Stephy-CaiXiaocheng
//链接:https://leetcode.cn/problems/minimum-depth-of-binary-tree/solutions/3901850/jian-dan-cu-bao-de-fang-fa-by-epic-gagar-mlue/
//来源:力扣(LeetCode)
//著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

思路2

  1. 层序遍历:遇到第一个叶子节点(左空右空),直接返回当前层数=最小深度
  2. 层序遍历用队列,先进先出保证顺序。

复杂度

时间复杂度: O(n)

空间复杂度: O(n)

核心代码

cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode* root) {
        if(!root) return 0;
        queue<TreeNode*> q;
        q.push(root);
        int depth=0;
        while(!q.empty()){
            depth++;//进入新一层,深度+1
            int sz=q.size();
            for(int i=0;i<sz;i++){
                TreeNode* node=q.front();
                q.pop();
                //第一个叶子结点,直接返回当前深度
                if(!node->left&&!node->right){
                    return depth;
                }if(node->left) q.push(node->left);
                if(node->right) q.push(node->right);
            }
        }
        return depth;
    }
};
相关推荐
宵时待雨8 分钟前
优选算法专题6:模拟
数据结构·c++·算法·leetcode·职场和发展
Liangwei Lin14 分钟前
LeetCode 35. 搜索插入位置
数据结构·算法·leetcode
L_090725 分钟前
【C++】STL— 封装红黑树以实现map 和 set
数据结构·c++
此生决int1 小时前
快速复习之数据结构篇——二叉树(三)
数据结构
Liangwei Lin1 小时前
LeetCode 78. 子集
数据结构·算法·leetcode
khalil10202 小时前
代码随想录算法训练营Day-48 单调栈02 | 42. 接雨水、84.柱状图中最大的矩形
数据结构·c++·算法·leetcode·单调栈·接雨水
大大杰哥2 小时前
Java集合框架(List/Set/Queue)核心总结与代码示例
java·数据结构
多加点辣也没关系2 小时前
数据结构与算法总章
数据结构·算法
hnjzsyjyj2 小时前
洛谷 P1305:新二叉树 ← DFS
数据结构·dfs
如君愿3 小时前
考研复习 Day 34 | 习题--计算机网络 第六章(应用层 下)、数据结构 查找算法(下)
数据结构·计算机网络·考研·课后习题