第九天 2021-3-11 每日刷四题
刷题模块:树 - 简单难度
一、【题】平衡二叉树
自顶向下,时间复杂度极高,涉及到许多无用的遍历
时间复杂度:O(n^2)
主要是调用height()多次自顶向下,没有在途中利用返回值。
递归本身时自底向上的
class Solution {
public:
bool isBalanced(TreeNode* root) {
if (!root) return true;
bool temp=abs(height(root->left)-height(root->right))<=1;
return temp && isBalanced(root->left) && isBalanced(root->right);
}
int height(TreeNode* root){
if(!root) return 0;
return max(height(root->left),height(root->right))+1;
}
};
官方:自底向上
class Solution {
public:
int height(TreeNode* root) {
if (root == NULL) {
return 0;
}
int leftHeight = height(root->left);
int rightHeight = height(root->right);
if (leftHeight == -1 || rightHeight == -1 || abs(leftHeight - rightHeight) > 1) {
return -1;
} else {
return max(leftHeight, rightHeight) + 1;
}
}
bool isBalanced(TreeNode* root) {
return height(root) >= 0;
}
};
二、【题】二叉树的最小深度
深度优先搜索
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root) return 0;
/* 下面这行可以删除,完全不影响逻辑*/
if(!root->left && !root->right) return 1;
else if(!root->left) return minDepth(root->right)+1;
else if(!root->right) return minDepth(root->left)+1;
else return min(minDepth(root->left),minDepth(root->right))+1;
}
};
/* 优化后 */
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root) return 0;
/* 上面一行和下面一行的逻辑填补了该句的逻辑*/
/*if(!root->left && !root->right) return 1;*/
else if(!root->left) return minDepth(root->right)+1;
else if(!root->right) return minDepth(root->left)+1;
else return min(minDepth(root->left),minDepth(root->right))+1;
}
};
ps:和官方深度优先搜索的解法虽然不一样,看上去复杂许多,但实际执行时完全一样,并不会执行多余的递归。
ps:代码第二行可以删除,完全不影响逻辑,这是有待提高的地方,这种代码笑死别人。
官方解法:广度优先搜索
当时考虑的实际问题是存在的,广度优先搜索需要借助队列,但在队列中会丢失高度信息。
官方使用了STL:pair保存了每一层的高度信息。
class Solution {
public:
int minDepth(TreeNode *root) {
if (root == nullptr) {
return 0;
}
queue<pair<TreeNode *, int> > que;
que.emplace(root, 1);
while (!que.empty()) {
TreeNode *node = que.front().first;
int depth = que.front().second;
que.pop();
if (node->left == nullptr && node->right == nullptr) {
return depth;
}
if (node->left != nullptr) {
que.emplace(node->left, depth + 1);
}
if (node->right != nullptr) {
que.emplace(node->right, depth + 1);
}
}
return 0;
}
};
三、STL:pair
pair是将2个数据组合成一组数据,当需要这样的需求时就可以使用pair。
C++ pair的基本用法总结(整理)
类模板:template<class T1,class T2> struct pair
参数:T1是第一个值的数据类型,T2是第二个值的数据类型。
功能:pair将一对值(T1和T2)组合成一个值,
这一对值可以具有不同的数据类型(T1和T2),
两个值可以分别用pair的两个公有函数first和second访问。
pair<T1, T2> p1; //创建一个空的pair对象(使用默认构造),它的两个元素分别是T1和T2类型,采用值初始化。
pair<T1, T2> p1(v1, v2); //创建一个pair对象,它的两个元素分别是T1和T2类型,其中first成员初始化为v1,second成员初始化为v2。
make_pair(v1, v2); // 以v1和v2的值创建一个新的pair对象,其元素类型分别是v1和v2的类型。
p1 < p2; // 两个pair对象间的小于运算,其定义遵循字典次序:如 p1.first < p2.first 或者 !(p2.first < p1.first) && (p1.second < p2.second) 则返回true。
p1 == p2; // 如果两个对象的first和second依次相等,则这两个对象相等;该运算使用元素的==操作符。
p1.first; // 返回对象p1中名为first的公有数据成员
p1.second; // 返回对象p1中名为second的公有数据成员