110. 平衡二叉树
class Solution {
public:
int getHeight(TreeNode* node) {
if (node == nullptr) return 0;
//采用后序遍历
int leftHeight = getHeight(node->left);
if (leftHeight == -1) return -1;
int rightHeight = getHeight(node->right);
if (rightHeight == -1) return -1;
//计算左右子树的高度差
if (abs(leftHeight - rightHeight) > 1) return -1;
else return 1 + max(leftHeight, rightHeight);
}
bool isBalanced(TreeNode* root) {
int result = getHeight(root);
//当返回值为-1时,说明已经不满足平衡二叉树的特性了
return result == -1 ? false : true;
}
};
257. 二叉树的所有路径
class Solution {
public:
//to_string 将数字转化成字符串
//这里有回溯的思想
//采用前序遍历
void getPath(TreeNode* node, vector<int>& path, vector<string>& paths) {
if (node == nullptr) return;
path.push_back(node->val);//path收集结点
//遍历到叶子结点就可以把路径放入到结果集中
if (node->left == nullptr && node->right == nullptr) {
//将数字组合成字符
string str = "";
int size = path.size();
for (int i = 0; i < size-1; i++) {
str += to_string(path[i]);
str += "->";
}
str += to_string(path[size-1]);
//加入到结果集合中
paths.push_back(str);
}
if (node->left) {
getPath(node->left, path, paths);
//回溯
path.pop_back();
}
if (node->right) {
getPath(node->right, path, paths);
//回溯
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> paths;//存放所有路径
vector<int> path;// 存放单条路径
getPath(root, path, paths);
return paths;
}
};
404. 左叶子之和
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (root == nullptr) return 0;
if (root->left == nullptr && root->right == nullptr) return 0;
//左
int leftVal = sumOfLeftLeaves(root->left);
if (root->left && root->left->left == nullptr && root->left->right == nullptr) {
leftVal = root->left->val;
}
//右
int rightVal = sumOfLeftLeaves(root->right);
//中
int sum = leftVal + rightVal;
return sum;
}
};