代码随想录算法训练营第17天
今日刷题3道:110.平衡二叉树,257. 二叉树的所有路径,404.左叶子之和
● 110.平衡二叉树
题目链接/文章讲解/视频讲解:https://programmercarl.com/0110.%E5%B9%B3%E8%A1%A1%E4%BA%8C%E5%8F%89%E6%A0%91.html
碎碎念:这里很巧妙,用-1表示判别失败,不是平衡二叉树。由于要递归返回高度,所以只能另写函数。
class Solution {
public:
int getHeight(TreeNode* node){
if(node == NULL) return 0;
int lefth = getHeight(node->left);
if(lefth == -1) return -1;
int righth = getHeight(node->right);
if(righth == -1) return -1;
return abs(lefth - righth) > 1 ? -1 : 1+ max(lefth,righth);
}
bool isBalanced(TreeNode* root) {
int result = getHeight(root);
if(result==-1) return false;
else return true;
}
};
● 257. 二叉树的所有路径
题目链接/文章讲解/视频讲解:https://programmercarl.com/0257.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%89%80%E6%9C%89%E8%B7%AF%E5%BE%84.html
class Solution {
private:
void traversal(TreeNode* cur, vector<int>& path, vector<string>& result) {
path.push_back(cur->val); // 中,中为什么写在这里,因为最后一个节点也要加入到path中
// 这才到了叶子节点
if (cur->left == NULL && cur->right == NULL) {
string sPath;
for (int i = 0; i < path.size() - 1; i++) {
sPath += to_string(path[i]);
sPath += "->";
}
sPath += to_string(path[path.size() - 1]);
result.push_back(sPath);
return;
}
if (cur->left) { // 左
traversal(cur->left, path, result);
path.pop_back(); // 回溯
}
if (cur->right) { // 右
traversal(cur->right, path, result);
path.pop_back(); // 回溯
}
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
vector<int> path;
if (root == NULL) return result;
traversal(root, path, result);
return result;
}
};
● 404.左叶子之和
题目链接/文章讲解/视频讲解:https://programmercarl.com/0404.%E5%B7%A6%E5%8F%B6%E5%AD%90%E4%B9%8B%E5%92%8C.html
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(root == NULL) return 0;
if(root->left == NULL && root->right == NULL) return 0;
int leftvalue = sumOfLeftLeaves(root->left);
if(root->left != NULL && root->left->left == NULL && root->left->right == NULL){
leftvalue = root->left->val;
}
int rightvalue = sumOfLeftLeaves(root->right);
int sum = leftvalue + rightvalue;
return sum;
}
};