1. 题目
给定一个二叉树,,找到它的最小深度。
最小深度是沿着最短路径从根节点到最近的叶节点的节点数。
2. 分析
本题类似于 Maximum Depth of Binary Tree
不同之处在于判断最小深度需要对叶子节点进行判断
不能取它左右子树的较小深度作为最小深度
因为如果一个节点只有左子树或只有右子树,其值为0
而在求最大深度的时候,一定会取较大值,所以不需要这个判断
注意不要遗漏对叶子节点的判断,将if(root->left == NULL)写成if(root->left)或是将min写成max
3. 代码
1)递归
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == NULL)
return 0;
if(root->left == NULL)
return minDepth(root->right) + 1;
if(root->right == NULL)
return minDepth(root->left) + 1;
return min(minDepth(root->left), minDepth(root->right)) + 1;
}
};
2)非递归
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == NULL)
return 0;
queue<TreeNode*> q;
q.push(root);
int level = 0;
while(!q.empty())
{
++level;
int len = q.size();
for(int i = 0; i < len; ++i)
{
TreeNode *node = q.front();
q.pop();
if(node->left == NULL && node->right == NULL)
return level;
if(node->left)
q.push(node->left);
if(node->right)
q.push(node->right);
}
}
return level;
}
};