解题思路
dfs:if条件判断
1.根节点为空
2.左右孩子为空
3.左孩子不为空:递归调用minDepth,把左孩子节点传入,跟depth比较,取两者更小的那个
4.右孩子不为空:递归调用minDepth,把右孩子节点传入,跟depth比较,取两者更小的那个
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == nullptr) return 0;
if(root->left == nullptr && root->right ==nullptr) return 1;
int min_depth = 63355;
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;
}
};
bfs:用队列一层一层比较,queue<pair<TreeNode*, int>> que,用que.empalce()方法插入。
1.根节点为空
2.插入root节点以及深度1到que
3.当que不为空时进行循环3~6步,取出que中存放的节点与深度
4.若节点没有左右孩子,则直接返回深度
5.若节点左孩子不为空,则将左孩子节点以及深度+1插入到que
6.若节点右孩子不为空,则将左孩子节点以及深度+1插入到que
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;
}
};