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

     1 /*
     2  * @lc app=leetcode.cn id=111 lang=cpp
     3  *
     4  * [111] 二叉树的最小深度
     5  */
     6 
     7 // @lc code=start
     8 /**
     9  * Definition for a binary tree node.
    10  * struct TreeNode {
    11  *     int val;
    12  *     TreeNode *left;
    13  *     TreeNode *right;
    14  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
    15  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    16  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    17  * };
    18  */
    19 class Solution {
    20 public:
    21     /*
    22     终止条件、返回值和递归过程:
    23 1)当前节点root为空时,说明此处树的高度为0,0也是最小值。
    24 2)当前节点root的左子树和右子树都为空时,说明此处树的高度为1,1也是最小值。
    25 3)如果为其他情况,则说明当前节点有值,且需要分别计算其左右子树的最小深度,返回最小深度+1,+1表示当前节点存在有1个深度。
    26 时间复杂度:O(n),n为树的节点数量。
    27     */
    28     int minDepth(TreeNode* root) {
    29          //当前节点root为空时,说明此处树的高度为0,0也是最小值
    30         if(!root) return 0;
    31         //当到达叶子节点时,叶子节点的深度为1
    32        if(root->left==nullptr&&root->right==nullptr) return 1;
    33        int m=INT_MAX;
    34        //如果为其他情况,则说明当前节点有值,且需要分别计算其左右子树的最小深度,返回最小深度+1,+1表示当前节点存在有1个深度
    35        if(root->left!=nullptr) m=min(minDepth(root->left),m);
    36        if(root->right!=nullptr) m=min(minDepth(root->right),m);
    37        return m+1;
    38     }
    39 };
    40 // @lc code=end
  • 相关阅读:
    CF833B The Bakery (线段树+DP)
    NOIP 2017 时间复杂度 (模拟)
    NOI 2018 屠龙勇士 (拓展中国剩余定理excrt+拓展欧几里得exgcd)
    中国剩余定理(excrt) 模板
    后缀自动机 模板
    luogu P4248 [AHOI2013]差异
    luogu P3975 [TJOI2015]弦论
    luogu P4770 [NOI2018]你的名字
    luogu P3726 [AH2017/HNOI2017]抛硬币
    luogu P3722 [AH2017/HNOI2017]影魔
  • 原文地址:https://www.cnblogs.com/yaodao12/p/13939300.html
Copyright © 2011-2022 走看看