class Solution {
public:
int height(TreeNode* root) {
if (!root) {
return 0;
}
int leftH = height(root->left);
int rightH = height(root->right);
if (leftH == - 1 || rightH == - 1 || abs(leftH - rightH) > 1) {
return -1;
}else {
return max(leftH, rightH) + 1;
}
}
bool isBalanced(TreeNode* root) {
return height(root) == -1 ? false : true;
}
};
回溯1
class Solution {
public:
void traversal(TreeNode* root, vector<int>& path, vector<string>& res) {
path.push_back(root->val);
if (!root->left && !root->right) {
string spath;
for (int i = 0; i < path.size() - 1; i++) {
spath += to_string(path[i]) + "->";
}
spath += to_string(path[path.size() - 1]);
res.push_back(spath);
return;
}
if (root->left) {
traversal(root->left, path, res);
path.pop_back();
}
if (root->right) {
traversal(root->right, path, res);
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<int> path;
vector<string> res;
if (!root) {
return res;
}
traversal(root, path, res);
return res;
}
};
回溯2
class Solution {
public:
void traversal(TreeNode* root, string path, vector<string>& res) {
path += to_string(root->val);
if (!root->left && !root->right) {
res.push_back(path);
return;
}
if (root->left) {
traversal(root->left, path + "->", res);
}
if (root->right) {
traversal(root->right, path + "->", res);
}
}
vector<string> binaryTreePaths(TreeNode* root) {
string path;
vector<string> res;
if (!root) {
return res;
}
traversal(root, path, res);
return res;
}
};
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (!root || (!root->left && !root->right)) {
return 0;
}
int leftSum = sumOfLeftLeaves(root->left);
if (root->left && !root->left->left && !root->left->right) {
leftSum = root->left->val;
}
int rightSum = sumOfLeftLeaves(root->right);
return leftSum + rightSum;
}
};