已经4.7了,但是我还在补前天的作业,不过请假在家,补就完事了!!加油!
目前优先掌握递归,其他方法读一遍理解。我一个非专业出身的,我卷什么??再卷我人就没了。
110.平衡二叉树 (优先掌握递归)
重点文字:
因为求深度可以从上到下去查 所以需要前序遍历(中左右)
而高度只能从下到上去查,所以只能后序遍历(左右中)
这题要求高度差为1,所以用后序。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int getHeight(TreeNode*node){
if(node == nullptr)return 0;
int leftdepth = getHeight(node->left); //左
if(leftdepth == -1)return -1;//这行忘了
int rightdepth = getHeight(node->right); //右
if(rightdepth == -1)return -1;//这行忘了,否则可就出现错误高度了
if(abs(leftdepth-rightdepth) > 1){ //中
return -1;
}
else{
return 1 + max(leftdepth,rightdepth);
}
}
bool isBalanced(TreeNode* root) {
return getHeight(root) == -1?false:true;
}
};
257. 二叉树的所有路径 (优先掌握递归)
这个感觉像是遍历,所以用中左右,前序。
然后就是递归法的退出条件和之前的不一样,是自己不nullptr,并且左右子节点都需要是nullptr。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void traversal(TreeNode *node,vector<int>&path,vector<string> &result ){
path.push_back(node->val); //中
if(node->left == nullptr && node->right == nullptr && node != nullptr){
string pathSt;
for(int i = 0;i < path.size() - 1;i++){
pathSt += to_string(path[i]);
pathSt += "->";
}
pathSt += to_string(path[path.size()-1]);
result.push_back(pathSt);
}
// path.push_back(node->val);//中写的地方太靠后
if(node->left != nullptr){ //左
traversal(node->left,path,result);
path.pop_back();
}
if(node->right != nullptr){ //右
traversal(node->right,path,result);
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<int>path;
vector<string>result;
if(root == nullptr)return result;
traversal(root,path,result);
return result;
}
};
目前还是不考虑精简版,怕混淆一些重要信息。
404.左叶子之和 (优先掌握递归)
看起来是深度问题,所以需要考虑前序(中左右)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int sumLeaves(TreeNode* node){
if(node == nullptr)return 0;
int sumleftLeaves = sumLeaves(node->left);
if(node->left != nullptr && node->left->right == nullptr && node->left->left == nullptr){
sumleftLeaves = node->left->val;
}
int sumrightLeaves = sumLeaves(node->right);
int sumLeaves1 = sumleftLeaves + sumrightLeaves;
return sumLeaves1;
}
int sumOfLeftLeaves(TreeNode* root) {
return sumLeaves(root);
}
};
先到这里,晚上继续,整第十八天