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;
    }
};


全部评论

相关推荐

一只乌鸦:这不才9月吗,26到明年毕业前能一直找啊,能拿下提前批,转正的,offer打牌的都是有两把刷子的,为什么非要跟他们比。如果别人是9本硕+金牌+好几段大厂实习呢?如果别人是双非通天代呢?如果别人是速通哥呢?,做好自己就行了,我们做不到他们一样提前杀死比赛,但晚点到终点也没啥关系吧
双非应该如何逆袭?
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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