111. 二叉树的最小深度
题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目描述
题目分析
- 递归法
注意最小深度求的是到叶子结点!!!,叶子结点没有孩子的结点。
如果左子树为空 右子树不为空 最小深度=1+右子树的深度
如果右子树为空 左子树不为空 最小深度=1+左子树的深度
左右子树都为空 最小深度=1+min(左子树深度,右子树深度)
class Solution {
public:
int getDept(TreeNode* root){
if(root == nullptr) return 0;
int leftDept = getDept(root->left);
int rightDept = getDept(root->right);
if(root->left == nullptr && root->right != nullptr){
return 1 + rightDept;
}else if(root->left != nullptr && root->right == nullptr){
return 1 + leftDept;
}else if(root->left == nullptr && root->right == nullptr){
return 1;
}
//左右都不为空
return 1 + min(leftDept, rightDept);
}
int minDepth(TreeNode* root) {
return getDept(root);
}
};
- 迭代法
class Solution {
public:
int minDepth(TreeNode* root) {
int res = 0;
queue<TreeNode*> que;
if(root != nullptr) que.push(root);
while(!que.empty()){
int n = que.size();
res++;
while(n--){
TreeNode* temp = que.front();
que.pop();
if(temp->left != nullptr) que.push(temp->left);
if(temp->right != nullptr) que.push(temp->right);
//在之前都没有左右孩子为空的时候 第一次到左右孩子为空 为最低点了
if(temp->left == nullptr && temp->right == nullptr) return res;
}
}
return res;
}
};