leetcode 二叉树最小深度

来源:互联网 发布:mac os怎么卸载软件 编辑:程序博客网 时间:2024/06/11 06:22

刚开始刷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