110.平衡二叉树 (优先掌握递归)
题目链接/文章讲解/视频讲解:代码随想录
子树深度不要相差超过1
由于是比较两个子树递归的结果,所以要取后
class Solution {
public:
int depth(TreeNode* root){
if(root == nullptr) return 0;
int leftdp,rightdp;
leftdp = depth(root->left);
if(leftdp == -1) return -1;
rightdp = depth(root->right);
if(rightdp == -1) return -1;
return abs(leftdp - rightdp)<= 1 ? max(leftdp,rightdp)+1 : -1;
}
bool isBalanced(TreeNode* root) {
return depth(root) == -1 ? false : true;
}
};
序位置。
没有去优化depth,每次都要向下,不知能否优化
257. 二叉树的所有路径 (优先掌握递归)
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> vec;
if(root == nullptr) return vec;
if(root->left == nullptr && root->right == nullptr){
vec.push_back(to_string(root->val));
return vec;
}
vector<string> addvec;
if(root->left!=nullptr){
addvec= binaryTreePaths(root->left);
vec.insert(vec.end(),addvec.begin(),addvec.end());
}
if(root->right!=nullptr){
addvec = binaryTreePaths(root->right);
vec.insert(vec.end(),addvec.begin(),addvec.end());
}
for(int i = 0; i<vec.size();i++){
vec[i] = to_string(root->val)+"->"+vec[i];
}
return vec;
}
};
学习了insert 函数用法
题目链接/文章讲解/视频讲解:代码随想录
404.左叶子之和 (优先掌握递归)
其实本题有点文字游戏,搞清楚什么是左叶子,剩下的就是二叉树的基本操作。
class Solution {
public:
int sum = 0;
int sumOfLeftLeaves(TreeNode* root) {
if(root == nullptr) return 0;
if(root->left!=nullptr&&root->left->left== nullptr && root->left->right==nullptr) sum+=root->left->val;
sumOfLeftLeaves(root->left);
sumOfLeftLeaves(root->right);
return sum;
}
};
题目链接/文章讲解/视频讲解:代码随想录