LeetCode111——Given a binary tree, find its minimum depth.

来源:互联网 发布:机械公差配合软件 编辑:程序博客网 时间:2024/05/21 13:21

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

之后发的文章就不翻译了,因为一般读这个文章的人都是刷LeetCode的人,读题目应该不成问题,我就不做多余的翻译了。

难度系数:

容易

实现

int minDepth(TreeNode *root) {    if (root == NULL)        return 0;    queue<TreeNode*> q;    q.push(root);    int mindepth = 1;    TreeNode* node;    while (!q.empty()) {        vector<TreeNode*> vt;        while (!q.empty()) {            node = q.front();            q.pop();            vt.push_back(node);        }        for (int i = 0; i < vt.size(); ++i) {            node = vt[i];            if (node->left == NULL && node->right == NULL) {                return mindepth;            }            if (node->left) {                q.push(node->left);            }            if (node->right) {                q.push(node->right);            }        }        mindepth += 1;    }    return mindepth;}

0 0
原创粉丝点击