学习目标
加强二叉树的递归。
过程
110.平衡二叉树 (优先掌握递归)
class Solution {
public:
int tree_height_isBalance(TreeNode* root) {
if(root==NULL){
return 0;
}
int leftHeight =tree_height_isBalance(root->left);
int rightHeight =tree_height_isBalance(root->right);
if((abs(leftHeight - rightHeight) > 1)|(leftHeight==-1)|(rightHeight==-1)){
return -1; // 那就表示不是平衡二叉树
}
else{
return max(leftHeight,rightHeight)+1;
}
}
bool isBalanced(TreeNode* root) {
return (tree_height_isBalance(root)>=0);
}
};
有点绕头,主要在递归的返回值上。
257. 二叉树的所有路径 (优先掌握递归)
class Solution {
public:
void binaryTreePaths_back_trace(TreeNode* root,string string){
string+=to_string(root->val);
if((root->left==NULL)&&(root->right==NULL)){
//然后表示现在是最后一个
string_vector.push_back(string);
}
string+="->";
if(root->left){
binaryTreePaths_back_trace(root->left,string);
}
if(root->right){
binaryTreePaths_back_trace(root->right,string);
}
}
vector<string> binaryTreePaths(TreeNode* root) {
//使用回溯的算法
if(root==NULL){
return string_vector;
}
string s;
binaryTreePaths_back_trace(root,s);
return string_vector;
}
vector<string> string_vector;
};
404.左叶子之和 (优先掌握递归)
class Solution {
public: //需要是子节点
int sumOfLeftLeaves_recursion(TreeNode* root,bool isleft){
if(root==NULL){
return 0;
}
int cur_value=0;
if((root->right==NULL)&&(root->left==NULL)){
if(isleft){
cur_value=root->val;
}
}
return cur_value+sumOfLeftLeaves_recursion(root->left,true)+ \
sumOfLeftLeaves_recursion(root->right,false);
}
int sumOfLeftLeaves(TreeNode* root) {
return sumOfLeftLeaves_recursion(root,false);
}
};
结论
除了第一题,其他的感觉还好,加油!