110.平衡二叉树
题目链接
110. 平衡二叉树
我的题解
/**
* 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 getHeight(TreeNode* root) {
if (root == nullptr) return 0;
int left_h = getHeight(root->left);
if (left_h == -1) return -1;
int left_r = getHeight(root->right);
if (left_r == -1) return -1;
if (abs(left_h - left_r) > 1) return -1;
return max(left_r, left_h) + 1;
}
bool isBalanced(TreeNode* root) {
return getHeight(root) == -1 ? false : true;
}
};
257. 二叉树的所有路径
题目链接
257. 二叉树的所有路径
我的题解
/**
* 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:
vector<string> res;
void binaryTreePaths_2(TreeNode * root, string path) {
if (root == nullptr) return;
path += to_string(root->val) + "->";
if (root->left == nullptr && root->right == nullptr) {
path = path.substr(0, path.size() - 2);
res.push_back(path);
}
binaryTreePaths_2(root->left, path);
binaryTreePaths_2(root->right, path);
}
vector<string> binaryTreePaths(TreeNode* root) {
string path = "";
binaryTreePaths_2(root, path);
return res;
}
};
404.左叶子之和
题目链接
404. 左叶子之和
我的题解
/**
* 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_2(TreeNode* root, bool isLeft) {
if (root == nullptr) return 0;
if (root->left == nullptr && root->right == nullptr && isLeft) {
//是一个左叶子结点
return root->val;
}
return sumOfLeftLeaves_2(root->left, true) + sumOfLeftLeaves_2(root->right, false);
}
int sumOfLeftLeaves(TreeNode* root) {
return sumOfLeftLeaves_2(root, false);
}
};