LeetCode第 111 题:二叉树的最小深度(C++)

111. 二叉树的最小深度 - 力扣(LeetCode)

注意叶子节点的定义。

因为求的是最小深度,所以可以使用层次遍历(bfs):

class Solution {
public:
    int minDepth(TreeNode* root) {
        if(!root) return 0;
        int res = 0;
        queue<pair<TreeNode*, int>> q;
        q.push({root, 1});
        while(!q.empty()){
            TreeNode* p = q.front().first;
            int val = q.front().second;
            q.pop();
            if(!p->left && !p->right){
                res = val;
                break;
            };//叶子节点
            if(p->left) q.push({p->left, val+1});
            if(p->right) q.push({p->right, val+1});
        }
        return res;
    }
};

本题只需要求最小深度即可,所有bfs借助的队列可以存储节点即可,我们一次处理二叉树的一层,当碰到叶子节点的时候,就break出来,具体看代码:

class Solution {
public:
    int minDepth(TreeNode* root) {
        if(!root) return 0;
        int res = 1, flag = 1;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            int len = q.size();
            for(int i = 0; i < len; ++i){//一次处理一层
                auto p = q.front();
                q.pop();
                if(!p->left && !p->right){//碰到叶子节点
                    flag = 0;
                    break;
                }   
                if(p->left) q.push(p->left);
                if(p->right) q.push(p->right);
            }
            if(!flag)   break;//碰到叶子节点
            ++res;//该层没有叶子节点,更新深度
        }
        return res;
    }
};

dfs:

class Solution {
public:
    int minDepth(TreeNode* root)
    {
        if (root == nullptr)    return 0;
        if(!root->left && !root->right) return 1; //叶子节点
        int min_dep = INT_MAX;
        if(root->left)  min_dep = min(min_dep, minDepth(root->left));
        if(root->right)  min_dep = min(min_dep, minDepth(root->right));

        return 1 + min_dep;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值