110.平衡二叉树 (优先掌握递归)
题目链接/文章讲解/视频讲解:代码随想录
class Solution {
public:
struct Info{
bool isB;
int height;
Info(bool isB, int height):isB(isB),height(height){}
};
bool isBalanced(TreeNode* root) {
return traversal(root).isB;
}
Info traversal(TreeNode* cur){
if(cur == nullptr){
return Info(true, 0);
}
Info linfo = traversal(cur->left);
Info rinfo = traversal(cur->right);
if(!linfo.isB || !rinfo.isB){
return Info(false, max(linfo.height,rinfo.height) + 1);
}
else{
if(abs(linfo.height - rinfo.height) < 2){
return Info(true, max(linfo.height,rinfo.height) + 1);
}
else{
return Info(false, max(linfo.height,rinfo.height) + 1);
}
}
}
};
257. 二叉树的所有路径 (优先掌握递归)
题目链接/文章讲解/视频讲解:代码随想录
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
constructPaths(root,"",result);
return result;
}
void constructPaths(TreeNode* cur, string path, vector<string>& result){
if(cur != nullptr){
path += to_string(cur->val);
if(cur->left == nullptr && cur->right == nullptr){
result.push_back(path);
return;
}
else{
path+= "->";
constructPaths(cur->left, path, result);
constructPaths(cur->right, path, result);
}
}
}
};
404.左叶子之和 (优先掌握递归)
题目链接/文章讲解/视频讲解:代码随想录
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
return sumTotal(root,false);
}
int sumTotal(TreeNode* cur, bool isLeft){
if(cur == nullptr) return 0;
if(cur->left == nullptr && cur->right == nullptr){
return isLeft ? cur->val : 0;
}
int leftSum = sumTotal(cur->left, true);
int RightSum = sumTotal(cur->right, false);
return leftSum + RightSum;
}
};