111. 二叉树的最小深度
难度:简单
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:2
示例 2:
输入:root = [2,null,3,null,4,null,5,null,6]
输出:5
提示:
- 树中节点数的范围在
[0, 105]
内 -1000 <= Node.val <= 1000
C++:迭代算法
思路:
与最大二叉树深度相反,当层序遍历时,如果存在一个节点没有左右孩子,说明这一层就为最小深度。、
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == nullptr) return 0;//如果根节点为null,则返回0
queue<TreeNode*> queue;
int minLevelCount = 0;
TreeNode* p;
queue.push(root);//将根节点入队
while(!queue.empty()){
int count = queue.size();//计算这一层有多少个节点
for(int i = 0; i < count; i++){
p = queue.front();//指向队头
//如果存在没有左右孩子的节点,说明这一层就为最小深度的一层
if(p->left == nullptr && p->right == nullptr){
minLevelCount++;//先加上本身这一层,再返回结果
return minLevelCount;
}
if(p->left != nullptr) queue.push(p->left);
if(p->right != nullptr) queue.push(p->right);
queue.pop();//弹出队头
}
minLevelCount++;
}
return minLevelCount;
}
};
C++:递归算法
class Solution {
public:
int minDepth(TreeNode* root) {
if(root==nullptr) return 0; //终止条件
if(root->left==nullptr) return minDepth(root->right)+1; //无左子树,返回右子树深度+1
if(root->right==nullptr) return minDepth(root->left)+1; //无右子树,返回左子树深度+1
return min(minDepth(root->left),minDepth(root->right))+1; //返回左右子树最小深度+1
}
};