leetcode 111. 二叉树的最小深度
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:2
递归
参数和返回值:参数为树的节点 TreeNode*,返回值 int ;
单层递归逻辑:当前节点左右子树都不为空则,最小深度等于其左右子树深度中最小的那个 + 1,有一个为空则最小深度等于不为空的子树深度 + 1,
终止条件:当前节点为空返回0;
int minDepth(TreeNode* root){
if(root == nullptr)
return 0;
if(root->left && !root->right)
return 1 + minDepth(root->left);
if(root->right && !root->left)
return 1 + minDepth(root->right);
return 1 + min(minDepth(root->left), minDepth(root->right));
}
迭代
利用队列每次保存一层的节点,当前节点中存在叶子节点且节点数大于1,则说明当前节点处于树的最小深度,否则继续添加下一层的所有非空节点并移除当前层的节点,直到队列为空
int minDepth(TreeNode* root) {
queue<TreeNode*> que;
if(root == nullptr)
return 0;
que.push(root);
int depth = 0;
while(!que.empty()){
++depth;
int size = que.size();
for(int i = 0; i < size; ++i){
TreeNode* node = que.front();
que.pop();
if(!node->left && !node->right && size > 1)
return depth;
if(node->left)
que.push(node->left);
if(node->right)
que.push(node->right);
}
}
return depth;
}