minimum-depth-of-binary-tree

minimum-depth-of-binary-tree

http://www.nowcoder.com/questionTerminal/e08819cfdeb34985a8de9c4e6562e724

//方法-:
class Solution {
public:
    int run(TreeNode *root) {
        if(!root) return 0;
        queue<pair<TreeNode*,int>> que;
        que.push(make_pair(root,1));
        pair<TreeNode*,int> p;
        int ans=0;
        while(!que.empty()){
            p=que.front();
            if(!(p.first->left)&&!(p.first->right)){
                return p.second;
            }
            que.pop();
            if(p.first->left) {que.push(make_pair(p.first->left,p.second+1));}
            if(p.first->right){que.push(make_pair(p.first->right,p.second+1));}
        }
    }
};

//方法二:
class Solution {
public:
    int run(TreeNode *root) {
        if(!root) return 0;
        queue<TreeNode*> que;
        que.push(root);
        TreeNode* p;
        int level=0;
        while(!que.empty()){
            level++;
            int size=que.size();
            while(size--){
                p=que.front();
                que.pop();
                if(!p->left&&!p->right) return level;
                if(p->left) que.push(p->left);
                if(p->right) que.push(p->right);
            }
        }
    }
};

//方法三:
class Solution {
public:
    int ans=0x3fffffff,n=0;
    void order(TreeNode *root){
        if(!root) return;
        ++n;
        if(!root->left&&!root->right){
            ans=min(ans,n);
        }
        order(root->left);
        order(root->right);
        --n;
    }
    int minDepth(TreeNode* root) {
        if(!root) return 0;
        order(root);
        return ans;
    }
};


全部评论

相关推荐

能干的三文鱼刷了10...:公司可能有弄嵌入式需要会画pcb的需求,而且pcb能快速直观看出一个人某方面的实力。看看是否有面试资格。问你问题也能ai出来,pcb这东西能作假概率不高
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-10 15:58
投个小米提前批试试水,先投一个岗位看看形势,不行就再沉淀一下投第二个岗位,莫辜负
Java抽象带篮子:我嘞个骚刚,已经开始研发6g了吗
投递小米集团等公司7个岗位
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务