【LeetCode】111. Minimum Depth of Binary Tree

问题描述

Given a binary tree, find its minimum depth.

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

二叉树最短路径问题。

问题分析

两种解法:

  1. 递归遍历,求每棵子树的最小路径
  2. 宽度优先搜索,或者说层次遍历,遍历树的每一层,找到了一个叶子节点就直接返回层数

代码

解法1 直接递归:
int minDepth(TreeNode* root) {
        if(root==0) return 0;
        if(root->left==0&&root->right==0) return 1;
        int l = minDepth(root->left);
        int r = minDepth(root->right);
        if(l==0) return r+1;
        if(r==0) return l+1;
        return l<r?l+1:r+1;
    }
解法2 宽度优先:
class Solution {
public:

    int minDepth(TreeNode* root) {
        if(root==0) return 0;
        queue<pair<TreeNode*,int> > q;
        q.push(make_pair(root,1));
        while(!q.empty()) {
            pair<TreeNode*,int> elem = q.front();
            TreeNode* p = elem.first;
            int level = elem.second;
            q.pop();
            if(p->left==0&&p->right==0) return level;
            if(p->left!=0) q.push(make_pair(p->left, level+1));
            if(p->right!=0) q.push(make_pair(p->right, level+1));
        }
        return 0;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值