【leetcode c++】111 Minimum Depth of Binary Tree

Minimum Depth of Binary Tree

 

Given a binary tree, find its minimumdepth.

The minimum depth is the number of nodesalong the shortest path from the root node down to the nearest leaf node.

 

之前做了一题叫最大深度,这题求一个最小深度,求最大深度的时候我没有刻意去区分当前节点是不是叶子节点,因为呢,不管是不是叶子节点,每个节点都有一个当前深度,只要找到最大深度就可以了,相当于是【找所有节点中的最大深度】。而这题呢,相当于是【找叶子节点深度中的最小一个】。所以我们在叶子节点的时候才会去做判断,其他节点则继续遍历。同样的,你也可以拿Maximum Depth of Binary Tree那题的代码来改改就OK了。


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode* root) {
    if(NULL == root) return 0;
    int lv = 0;
    int minLv = -1;
    Lv(root, lv, minLv);
    return minLv + 1;
    }
    
    void Lv(TreeNode* root, int lv, int& minLv) {
    if(NULL == root) return;
    if(!root->left && !root->right)
    {
        if(-1 == minLv || lv < minLv) minLv = lv;
    }
    Lv(root->left, lv + 1, minLv);
    Lv(root->right, lv + 1, minLv);
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值