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;
    }
};
相关推荐
liuyao_xianhui7 分钟前
map和set_C++
java·开发语言·数据结构·c++·算法·宽度优先
脱氧核糖核酸__1 小时前
LeetCode热题100——41.缺失的第一个正数(题解+答案+要点)
数据结构·c++·算法·leetcode·哈希算法
努力努力再努力wz2 小时前
【MySQL入门系列】:不只是建表:MySQL 表约束与 DDL 执行机制全解析
android·linux·服务器·数据结构·数据库·c++·mysql
贾斯汀玛尔斯2 小时前
每天学一个算法-- 归并排序(Merge Sort)
数据结构·算法·排序算法
算法鑫探2 小时前
算法中的二分法(二分查找)详解及示例
c语言·数据结构·算法·新人首发
澈2072 小时前
排序算法入门:冒泡、选择、插入排序详解
数据结构·算法·排序算法
John.Lewis2 小时前
C++加餐课-二叉树:进阶算法
数据结构·c++·算法
会编程的土豆3 小时前
【数据结构与算法】栈的应用
数据结构·c++·算法
Mem0rin3 小时前
[Java/数据结构]PriorityQueue
java·数据结构
m0_716765233 小时前
数据结构--栈的插入、删除、查找详解
开发语言·数据结构·c++·经验分享·学习·青少年编程·visual studio