您的位置:首页 > 其它

[LeetCode] 111. Minimum Depth of Binary Tree

2017-07-31 20:56 363 查看
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.

// DFS
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == nullptr) return 0;
if (!root->right) return minDepth(root->left) + 1;  // only left branch
if (!root->left) return minDepth(root->right) + 1;  // only right branch
return min(minDepth(root->left), minDepth(root->right)) + 1;    // no or two
}
};


// DFS
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == nullptr)
return 0;
if (root->left == nullptr && root->right == nullptr)
return 1;

int minDep = INT_MAX;
if (root->left)
minDep = min(minDep, minDepth(root->left) + 1);

if (root->right)
minDep = min(minDep, minDepth(root->right) + 1);

return minDep;
}
};


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

int MinDepth = INT_MAX;
minDepth(root, 1, MinDepth);

return MinDepth;
}
private:
void minDepth(TreeNode *root, int level, int& MinDepth) {
if (root->left == nullptr && root->right == nullptr)
MinDepth = min(level, MinDepth);

if (root->left)
minDepth(root->left, level + 1, MinDepth);

if (root->right)
minDepth(root->right, level + 1, MinDepth);
}
};


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

int level = 1;

queue<TreeNode *> q;
q.push(root);
q.push(nullptr);

while (!q.empty()) {
TreeNode *ptn = q.front();
q.pop();

if (ptn == nullptr) {
level++;
if (!q.empty())
q.push(nullptr);
continue;
}

if (ptn->left == nullptr && ptn->right == nullptr)
break;
else {
if (ptn->left) q.push(ptn->left);
if (ptn->right) q.push(ptn->right);
}
}

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