一、题目
给定一个二叉树,找出其最小深度。最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
二、解答
事实胜于雄辩->我的数据结构快忘光咯!(当然很有可能没学好)
言归正传,这道题其实是一个搜索二叉树的题目。提到搜索,那就让人联想到——广度优先搜索和深度优先搜索,下面这篇文章很好地解释了这两个概念:http://t.csdnimg.cn/KhtKO
1.深度优先搜索
代码如下:
class Solution {
public:
int minDepth(TreeNode *root) {
if (root == nullptr) {
return 0;
}
if (root->left == nullptr && root->right == nullptr) {
return 1;
}
int min_depth = INT_MAX;
if (root->left != nullptr) {
min_depth = min(minDepth(root->left), min_depth);
}
if (root->right != nullptr) {
min_depth = min(minDepth(root->right), min_depth);
}
return min_depth + 1;
}
};
作者:力扣官方题解
链接:https://leetcode.cn/problems/minimum-depth-of-binary-tree/solutions/382646/er-cha-shu-de-zui-xiao-shen-du-by-leetcode-solutio/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
这种方法的效率还不错。
2.广度优先搜索
这里很有意思,用到了queue和pair。
这是优先队列的emplace的相关介绍:http://t.csdnimg.cn/kVwcT
这是pair的基本用法总结:http://t.csdnimg.cn/RJEL8
代码如下:
class Solution {
public:
int minDepth(TreeNode *root) {
if (root == nullptr) {
return 0;
}
queue<pair<TreeNode *, int> > que;
que.emplace(root, 1);
while (!que.empty()) {
TreeNode *node = que.front().first;
int depth = que.front().second;
que.pop();
if (node->left == nullptr && node->right == nullptr) {
return depth;
}
if (node->left != nullptr) {
que.emplace(node->left, depth + 1);
}
if (node->right != nullptr) {
que.emplace(node->right, depth + 1);
}
}
return 0;
}
};
作者:力扣官方题解
链接:https://leetcode.cn/problems/minimum-depth-of-binary-tree/solutions/382646/er-cha-shu-de-zui-xiao-shen-du-by-leetcode-solutio/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
以上两种方式的效率好像差不多。
供君参考。