代码随想录算法训练营第17天| 110.平衡二叉树、257.二叉树的所有路径、404. 左叶子之和
110.平衡二叉树
求高度适合使用后序遍历,使用递归方法:
class Solution {
public:
// 范围以该节点为根节点的二叉树的高度,如果不是平衡二叉树则返回-1
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;
return abs(leftHeight - rightHeight) > 1 ? -1 : 1
+ max(leftHeight, rightHeight);
}
bool isBalanced(TreeNode* root) {
return getHeight(root) == -1 ? false : true;
}
};
257.二叉树的所有路径
to_string() : int转string
class Solution {
public:
void travelsal(TreeNode* cur, vector<int>& path, vector<string>& res) {
// 最后一个叶子节点也得加入到path中
path.push_back(cur->val);
if (cur->left == nullptr && cur->right == nullptr) {
string sPath;
for (int i = 0; i < path.size() - 1; ++i) {
sPath += to_string(path[i]);
sPath += "->";
}
sPath += to_string(path[path.size() - 1]);
res.push_back(sPath);
return ;
}
if (cur->left != nullptr) {
travelsal(cur->left, path, res);
path.pop_back(); // 回溯
}
if (cur->right != nullptr) {
travelsal(cur->right, path, res);
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
vector<int> path;
if (root == nullptr) return res;
travelsal(root, path, res);
return res;
}
};
404. 左叶子之和
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (root == nullptr) return 0;
if (root->left == nullptr && root->right == nullptr) return 0;
int leftValue = sumLeftLeaves(root->left);
if (root->left != nullptr && root->left->left == nullptr && root->left->right == nullptr) {
leftValue = root->left->value;
}
int rightValue = sumOfLeftLeaves(root->right);
int sum = leftValue + rightValue;
return sum;
}
};
精简代码之后:
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (root == nullptr) return 0;
int leftValue = 0;
if (root->left != nullptr && root->left->left == nullptr && root->left->right == nullptr) {
leftValue = root->left->val;
}
return leftValue + sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
}
};
还有一种写法:
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
int sum = 0;
if (root == nullptr) return 0;
if (root->left != nullptr && root->left->left == nullptr && root->left->right == nullptr) {
sum = root->left->val;
}
sum += sumOfLeftLeaves(root->left);
sum += sumOfLeftLeaves(root->right);
return sum;
}
};