110.平衡二叉树 ,
class Solution {
public:
int get_height(TreeNode* root){ // 当前节点的高度等于左右子树的最大高度,若出现左右子树的高度差大于一则报错
if(root == nullptr){
return 0;
}
int left_height = 0;
if(root->left != nullptr){
left_height = get_height(root->left);
if(left_height == -1){
return -1;
}
}
int right_height = 0;
if(root->right != nullptr){
right_height = get_height(root->right);
if(right_height == -1){
return -1;
}
}
return abs(right_height - left_height) > 1 ? -1 : max(left_height, right_height) + 1;
}
bool isBalanced(TreeNode* root) {
int ans = get_height(root);
return ans != -1;
}
};
257. 二叉树的所有路径
抄的官方答案,。。
class Solution {
public:
void construct_paths(TreeNode* root, string path, vector<string>& paths) {
if (root != nullptr) {
path += to_string(root->val);
if (root->left == nullptr && root->right == nullptr) { // 当前节点是叶子节点
paths.push_back(path); // 把路径加入到答案中
} else {
path += "->"; // 当前节点不是叶子节点,继续递归遍历
construct_paths(root->left, path, paths);
construct_paths(root->right, path, paths);
}
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> paths;
construct_paths(root, "", paths);
return paths;
}
};
404.左叶子之和
class Solution {
public:
void sumOfLeftLeaves(TreeNode* root, int ifLeft, int &ans){// ans 不用回溯,所以是引用
if(root != nullptr){
if(root->left == nullptr && root->right == nullptr && ifLeft == 1){
ans += root->val; // ans 不用回溯
}
if(root->left != nullptr){
sumOfLeftLeaves(root->left, 1, ans);
}
if(root->right != nullptr){
sumOfLeftLeaves(root->right, 0, ans);
}
}
}
int sumOfLeftLeaves(TreeNode* root) {
int res = 0;
sumOfLeftLeaves(root, 0, res);
return res;
}
};
222.完全二叉树的节点个数
222. 完全二叉树的节点个数 - 力扣(LeetCode)
class Solution {
public:
// 递归O(n)
void travel(TreeNode* root, int &num){
if(root == nullptr){
return ;
}
num++;
if(root->left != nullptr){
travel(root->left, num);
}
if(root->right != nullptr){
travel(root->right, num);
}
}
int countNodes(TreeNode* root) {
if(root == nullptr){
return 0;
}
TreeNode* left_node = root->left;
TreeNode* right_node = root->right;
int left_sum = 0, right_sum = 0;
while(left_node != nullptr){
left_node = left_node->left;
left_sum++;
}
while(right_node != nullptr){
right_node = right_node->right;
right_sum++;
}
if(right_sum == left_sum){
return (2 << left_sum) - 1; // 这颗子树为满二叉树 2 ^ (left_sum + 1) - 1
}
return countNodes(root->left) + countNodes(root->right) + 1; // 不是满二叉树
}
};

被折叠的 条评论
为什么被折叠?



