leetcode 二叉树最小深度

刚开始刷leetcode,因为以前刷OJ,代码写的比较随意,所以这里一看就给个类就楞了,

想了一会不纠结这个了,开始做题,不敢定义全局变量,后来定义了static变量,写了个递归,结果可能姿势不对,

递归段溢出了,然后突然想到用队列套pair,最终过了,看了下讨论区,才发现递归的正确姿势,自己犯傻了,

贴上自己的代码:

class Solution {
public:
    int run(TreeNode *root) {
        if(root==NULL)
            return 0;
      queue<pair<TreeNode *,int> > q;
        q.push(make_pair(root,1));
        int min=10000000;
      while(!q.empty()){
         pair<TreeNode *,int> p;
          p=q.front();
          q.pop();
          TreeNode *tem=p.first;
          if(tem->left!=NULL)
              q.push(make_pair(tem->left,p.second+1));
          if(tem->right!=NULL)
              q.push(make_pair(tem->right,p.second+1));
          if(tem->left==NULL&&tem->right==NULL){
              if(p.second<min)
              min=p.second;
          }
      }
        return min;
    }
};
递归返回值也是可以叠加的,不一定需要多个参数,或者多个变量:

class Solution {
public:
    int run(TreeNode *root) {
        if(root==NULL)
            return 0;
      	if(root->left==NULL)
            return run(root->right)+1;
        if(root->right==NULL)
            return run(root->left)+1;
        else
            return min(run(root->left),run(root->right))+1;
    }
};
其实局限于格式的话,可以另外写个函数,让给的函数调用那个函数。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值