1、平衡二叉树
110. 平衡二叉树 - 力扣(LeetCode)
class Solution {
public:
int getHeight(TreeNode* root) {
if (!root) return 0;
int leftheight = getHeight(root->left);
if (leftheight == -1) return -1;
int rightheight = getHeight(root->right);
if (rightheight == -1) return -1;
if (abs(leftheight - rightheight) > 1) return -1;
return 1 + max(leftheight, rightheight);
}
bool isBalanced(TreeNode* root) {
if (getHeight(root) == -1) return false;
return true;
}
};
2、二叉树的所有路径
257. 二叉树的所有路径 - 力扣(LeetCode)
class Solution {
public:
void traversal(TreeNode* root, vector<int>& path, vector<string>& result) {
// 前序遍历
path.push_back(root->val);
// 终止条件
if (!root->left && !root->right) {
string str = "";
for (int i = 0; i < path.size() - 1; i++) {
str += to_string(path[i]);
str += "->";
}
str += to_string(path.back());
result.push_back(str);
}
// 左
if (root->left) {
traversal(root->left, path, result);
// 回溯
path.pop_back();
}
// 右
if (root->right) {
traversal(root->right, path, result);
// 回溯
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<int> path;
vector<string> result;
traversal(root, path, result);
return result;
}
};
3、左叶子之和
404. 左叶子之和 - 力扣(LeetCode)
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (!root) return 0;
if (!root->left && !root->right) return 0;
int left = sumOfLeftLeaves(root->left);
if (root->left && !root->left->left && !root->left->right) {
left = root->left->val;
}
int right = sumOfLeftLeaves(root->right);
return right + left;
}
};