110.平衡二叉树 (优先掌握递归)
左右子树高度差小于1为平衡二叉树,但每个节点都需要满足这个条件。
class Solution {
public:
int height(TreeNode* root) {
if (root == NULL) {
return 0;
} else {
return max(height(root->left), height(root->right)) + 1;
}
}
bool isBalanced(TreeNode* root) {
if (root == NULL) {
return true;
} else {
return abs(height(root->left) - height(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}
}
};
257. 二叉树的所有路径 (优先掌握递归)
这个要回溯
class Solution {
public:
void travseral(TreeNode *cur, vector<int> &path,vector<string> &result){
path.push_back(cur->val);
if(cur->left == nullptr && cur->right == nullptr){
string sPath;
for(int i = 0; i < path.size() - 1; i++){
sPath += to_string(path[i]);
sPath += "->";
}
sPath += to_string(path[path.size() - 1]);
result.push_back(sPath);
}
if(cur->left){
travseral(cur->left,path,result);
path.pop_back();
}
if(cur->right){
travseral(cur->right,path,result);
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<int> path;
vector<string> result;
if(root == nullptr) return result;
travseral(root,path,result);
return result;
}
};
404.左叶子之和 (优先掌握递归)
左叶子的判断方式是:
if(root->left != nullptr && root->left->left == nullptr && root->left->right == nullptr)
class Solution {
public:
int sumLeft(TreeNode *root, int &sum){
if(root == nullptr) return 0;
if(root->left != nullptr && root->left->left == nullptr && root->left->right == nullptr){
sum += root->left->val;
}
sumLeft(root->left, sum);
sumLeft(root->right,sum);
return sum;
}
int sumOfLeftLeaves(TreeNode* root) {
if(!root) return 0;
int sum = 0;
return sumLeft(root,sum);
}
};