平衡二叉树
class Solution {
public:
int GetH(TreeNode* root)
{
if (root == nullptr)
return 0;
int len_left = GetH(root->left);
int len_right = GetH(root->right);
if (len_left > len_right)
return len_left + 1;
else
return len_right + 1;
}
bool isBalanced(TreeNode* root) {
if (root == nullptr)
return true;
int height_left = GetH(root->left);
int height_right = GetH(root->right);
if (abs(height_left - height_right) <= 1 && isBalanced(root->left) && isBalanced(root->right))
return true;
else
return false;
}
};
二叉树的所有路径
pass
左叶子之和
why?不太理解
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (root == nullptr)
return 0;
int sum_left = sumOfLeftLeaves(root->left);
if (root->left != nullptr && root->left->left == nullptr &&root->left->right == nullptr)
{
sum_left = root->left->val;
}
int sum_right = sumOfLeftLeaves(root->right);
return sum_left + sum_right;
}
};