代码随想录算法训练营第37期 第十七天 | LeetCode110.平衡二叉树、257. 二叉树的所有路径、404.左叶子之和
一、110.平衡二叉树
解题代码C++:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int getDepth(TreeNode* node)
{
if(!node) return 0;
return 1 + max(getDepth(node->left), getDepth(node->right));
}
bool isBalanced(TreeNode* root) {
if(!root) return true;
return abs(getDepth(root->left) - getDepth(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}
};
题目链接/文章讲解/视频讲解:
https://programmercarl.com/0110.%E5%B9%B3%E8%A1%A1%E4%BA%8C%E5%8F%89%E6%A0%91.html
二、257. 二叉树的所有路径
解题代码C++:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void traversal(TreeNode* cur, string path, vector<string>& result)
{
path += to_string(cur->val);
if(cur->left == NULL && cur->right == NULL)
{
result.push_back(path);
return;
}
if(cur->left) traversal(cur->left, path + "->", result);
if(cur->right) traversal(cur->right, path + "->", result);
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
string path;
if(!root) return result;
traversal(root, path, result);
return result;
}
};
题目链接/文章讲解/视频讲解:
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
三、404.左叶子之和
解题代码C++:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(!root) return 0;
int leftValue = 0;
if(root->left != NULL && root->left->left == NULL && root->left->right == NULL)
leftValue += root->left->val;
return leftValue + sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
}
};
题目链接/文章讲解/视频讲解:
https://programmercarl.com/0404.%E5%B7%A6%E5%8F%B6%E5%AD%90%E4%B9%8B%E5%92%8C.html