代码随想录算法训练营第13天|110. 平衡二叉树、257. 二叉树的所有路径、404. 左叶子之和
110. 平衡二叉树
提交代码
class Solution {
public:
int height(TreeNode* node)
{
if(node == nullptr) return 0;
return 1 + max(height(node -> left), height(node -> right));
}
bool isBalanced(TreeNode* root) {
if(root == nullptr) return true;
return (abs(height(root -> left) - height(root -> right)) <= 1) && isBalanced(root -> left) && isBalanced(root -> right);
}
};
257. 二叉树的所有路径
提交代码(方法)
class Solution {
public:
void tranversal(TreeNode* node, vector<int>& path, vector<string>& result)
{
if(node == nullptr) return;
path.push_back(node -> val);
if(node -> left == nullptr && node -> right == nullptr)
{
string res{
};
for(int i = 0; i < path.size(); i++)
{
if(i == path.size() - 1)
res += to_string(path[i]);
else
{
res += to_string(path[i]);
res += "->";
}
}
result.push_back(res);
return;
}
if(node -> left)
{
tranversal(node -> left, path, result);
path.pop_back();
}
if(node -> right)
{
tranversal(node -> right, path, result);
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<int> path;
vector<string> result;
tranversal(root, path, result);
return result;
}
};
404. 左叶子之和
提交代码
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(root == nullptr) return 0;
if(root -> left == nullptr && root -> right == nullptr) return 0;
int left = 0;
if(root -> left != nullptr && root -> left -> left == nullptr && root -> left -> right == nullptr) left = root -> left -> val;
return left + sumOfLeftLeaves(root -> left) + sumOfLeftLeaves(root -> right);
}
};
总结
日期: 2023 年 3 月 31 日
学习时长: 1 h 0 m
难度: ★ \bigstar ★ ★ \bigstar ★
累计完成题目数量: 51
距离目标还有数量: 249
小结:
- 先写两道题,明天再看把。