您的位置:首页 > 其它

[LeetCode] 111. Minimum Depth of Binary Tree

2017-06-27 19:42 369 查看
Given a binary tree, find its minimum depth.

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

// BFS
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == nullptr) return 0;

int Depth = 1;
queue<TreeNode *> q;
q.push(root);
q.push(nullptr);

while (!q.empty()) {
TreeNode *ptn = q.front();
q.pop();
if (ptn == nullptr) {
Depth++;
q.push(nullptr);
continue;
}

if (ptn->left == nullptr && ptn->right == nullptr)
break;

if (ptn->left)
q.push(ptn->left);

if (ptn->right)
q.push(ptn->right);
}

return Depth;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: