二叉树的最小深度直觉上和二叉树的最大深度差不多,但其实存在一个误区,也就是根节点的左子树或者右子树不存在,如果不加判断条件,很容易将二叉树的最小深度求为1
且深度为二叉树到叶子结点的距离,而叶子结点为左右子树都为空的节点,在求深度时要判断是否为叶子结点
写递归法的代码时,要注意节点的左右子树情况:(1)左子树存在,右子树不存在,最小深度为1+左子树深度(2)右子树存在,左子树不存在,最小深度为1+右子树深度。代码如下:
class Solution {
public:
int getDepth(TreeNode* root){
if(root == nullptr) return 0;
int ldepth = getDepth(root->left);
int rdepth = getDepth(root->right);
if(root->left != nullptr && root->right == nullptr) return 1 + ldepth;
if(root->left == nullptr && root->right != nullptr) return 1 + rdepth;
int depth = 1 + min(ldepth, rdepth);
return depth;
}
int minDepth(TreeNode* root) {
return getDepth(root);
}
};
写迭代法代码时,要判断节点是否为叶子节点,是叶子结点时返回深度,即为二叉树的最小深度
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == NULL) return 0;
int depth = 0;
queue<TreeNode*> que;
que.push(root);
while(!que.empty()) {
int size = que.size();
depth++; // 记录最小深度
for (int i = 0; i < size; i++) {
TreeNode* node = que.front();
que.pop();
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
if (!node->left && !node->right) { // 当左右孩子都为空的时候,说明是最低点的一层了,退出
return depth;
}
}
}
return depth;
}
};