leetcode 111

题目描述:

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.

 

解法一:非递归方式,使用层序遍历的方法,借助队列,思想比较简单。

int minDepth(TreeNode* root)
{
    int res = 0;
    if(!root)
        return res;
    else
    {
        res = 1;
        queue<TreeNode*> q;
        q.push(root);
        int layer_size_left = q.size();

        while(!q.empty())
        {
            TreeNode * temp = q.front();
            q.pop();
            -- layer_size_left;
            if(temp->left)
                q.push(temp->left);

            if(temp->right)
                q.push(temp->right);

            if(!temp->left && !temp->right)
                return res;

            if(layer_size_left == 0)
            {
                ++ res;
                layer_size_left = q.size();
            }
        }
    }
    return res;

}

解法二:递归方式,递归方式看上去更简洁一些,而且更易扩展,比如稍作修改即可解出最大深度等,当然非递归方式使用层序遍历解最大深度也不难。

int minDepth(TreeNode* root)
{
    if(!root)
        return 0;
    int l = minDepth(root->left);
    int r = minDepth(root->right);

    if(!l)
        return 1 + r;
    if(!r)
        return 1 + l;

    return l > r ? 1 + r : 1 + l;
}

两者的运行效率差不太多,leetcode上显示运行时间都是9ms,但是都不是最快的解法,应该还有可以优化的地方!这应该是我接下来努力的方向。

 

转载于:https://www.cnblogs.com/maizi-1993/p/5892696.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值