110.平衡二叉树
题目链接:https://leetcode.cn/problems/balanced-binary-tree/
文章讲解:https://programmercarl.com/0110.%E5%B9%B3%E8%A1%A1%E4%BA%8C%E5%8F%89%E6%A0%91.html
视频讲解:https://www.bilibili.com/video/BV1Ug411S7my/
class Solution {
public:
int getHeight(TreeNode* node) {
if (node == NULL) {
return 0;
}
int leftHeight = getHeight(node->left);
if (leftHeight == -1) return -1;
int rightHeight = getHeight(node->right);
if (rightHeight == -1) return -1;
return abs(leftHeight - rightHeight) > 1 ? -1 : 1 + max(leftHeight, rightHeight);
}
bool isBalanced(TreeNode* root) {
return getHeight(root) == -1 ? false : true;
}
};
257. 二叉树的所有路径
题目链接:https://leetcode.cn/problems/binary-tree-paths/description/
文章讲解:https://programmercarl.com/0257.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%89%80%E6%9C%89%E8%B7%AF%E5%BE%84.html
视频讲解:https://www.bilibili.com/video/BV1ZG411G7Dh/
class Solution {
public:
void traversal(TreeNode *node ,vector<int> &path,vector<string> &result)
{
path.push_back(node->val);
if(node ->left == NULL && node->right == NULL)
{
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);
return ;
}
if(node->left)
{
traversal(node->left,path,result);
path.pop_back();
}
if(node->right)
{
traversal(node->right,path,result);
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
vector<int> path;
if(root == NULL)
{
return result;
}
traversal(root,path,result);
return result;
}
};
404.左叶子之和
题目链接:https://leetcode.cn/problems/sum-of-left-leaves/
文章讲解:https://programmercarl.com/0404.%E5%B7%A6%E5%8F%B6%E5%AD%90%E4%B9%8B%E5%92%8C.html
视频讲解:https://www.bilibili.com/video/BV1GY4y1K7z8/?vd_source=5287cb6df25410935566fc8f0d951a5a
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (root == NULL) return 0;
if (root->left == NULL && root->right== NULL) return 0;
int leftValue = sumOfLeftLeaves(root->left);
if (root->left && !root->left->left && !root->left->right) {
leftValue = root->left->val;
}
int rightValue = sumOfLeftLeaves(root->right);
int sum = leftValue + rightValue;
return sum;
}
};