111. 二叉树的最小深度
问题描述
思路
直觉上好像和求最大深度差不多,其实还是差不少的。
遍历顺序上是后序遍历(因为要比较递归返回之后的结果),但在处理中间节点的逻辑上,最大深度很容易理解,最小深度可有一个误区,如图:
题目中说的是: 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 注意是叶子节点。
1、递归法
①确定递归函数的参数和返回值:
参数为要传入的二叉树根节点,返回的是int类型的深度。
int getDepth(TreeNode* node)
②确定终止条件:
遇到空节点返回0,表示当前节点的高度为0。
if (node == NULL) return 0;
③确定单层递归的逻辑:
- 左子树为空,右子树不为空,最小深度是 1 + 右子树的深度。
- 右子树为空,左子树不为空,最小深度是 1 + 左子树的深度
- 左右子树都不为空,返回左右子树深度最小值 + 1
int leftDepth = getDepth(node->left); // 左
int rightDepth = getDepth(node->right); // 右
// 中
// 当一个左子树为空,右不为空,这时并不是最低点
if (node->left == NULL && node->right != NULL) {
return 1 + rightDepth;
}
// 当一个右子树为空,左不为空,这时并不是最低点
if (node->left != NULL && node->right == NULL) {
return 1 + leftDepth;
}
int result = 1 + min(leftDepth, rightDepth);
return result;
整体代码如下:
class Solution {
public:
int getDepth(TreeNode* node) {
if (node == NULL) return 0;
int leftDepth = getDepth(node->left); // 左
int rightDepth = getDepth(node->right); // 右
// 中
// 当一个左子树为空,右不为空,这时并不是最低点
if (node->left == NULL && node->right != NULL) {
return 1 + rightDepth;
}
// 当一个右子树为空,左不为空,这时并不是最低点
if (node->left != NULL && node->right == NULL) {
return 1 + leftDepth;
}
int result = 1 + min(leftDepth, rightDepth);
return result;
}
int minDepth(TreeNode* root) {
return getDepth(root);
}
};
精简代码如下:
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == NULL) return 0;
if (root->left == NULL && root->right != NULL) {
return 1 + minDepth(root->right);
}
if (root->left != NULL && root->right == NULL) {
return 1 + minDepth(root->left);
}
return 1 + min(minDepth(root->left), minDepth(root->right));
}
};
2、迭代法
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++; // 记录最小深度
int flag = 0;
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) {
// 当左右孩子都为空的时候,说明是最低点的一层了,退出
flag = 1;
break;
}
}
if (flag == 1) break;
}
return depth;
}
};