代码随想录算法训练营Day17 | 110.平衡二叉树 257. 二叉树的所有路径 404.左叶子之和
LeetCode 110.平衡二叉树
题目链接:LeetCode 110.平衡二叉树
思路:
1.递归法 分别求左右,取差的绝对值。
//递归法
class Solution {
public:
int getHeight(TreeNode* node){
if(!node) 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+max(leftHeight, rightHeight): -1;
}
bool isBalanced(TreeNode* root) {
if(!root) return true;
return getHeight(root) == -1 ? false : true;
}
};
LeetCode 257. 二叉树的所有路径
思路:
1.分别传入path和res
class Solution {
public:
void traversal(TreeNode* node, vector<int>& path, vector<string>& res){
path.push_back(node->val);
if(!node->left && !node->right){
string sPath;
for(int p:path) sPath += to_string(p)+"->";
sPath.pop_back();
sPath.pop_back();
res.push_back(sPath);
return;
}
if(node->left) {
traversal(node->left, path, res);
path.pop_back();
}
if(node->right) {
traversal(node->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;
}
};
//传值法不需要pop
class Solution {
public:
void traversal(TreeNode* node, string path, vector<string>& res){
path += to_string(node->val);
if(!node->left && !node->right){
res.push_back(path);
return;
}
if(node->left) traversal(node->left, path+"->", res);
if(node->right) traversal(node->right, path+"->", res);
}
vector<string> binaryTreePaths(TreeNode* root) {
string path;
vector<string> res;
if(!root) return res;
traversal(root, path, res);
return res;
}
};
注意 :
- 注意path和res都是传地址,用&
- 如果path传值,不需要pop
LeetCode 404.左叶子之和
题目链接:LeetCode 404.左叶子之和
思路:
通过父节点判断是否为左叶子
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (root == NULL) return 0;
if (root->left == NULL && root->right== NULL) return 0;
int sum = 0;
sum += sumOfLeftLeaves(root->left); // 左
sum += sumOfLeftLeaves(root->right); // 右
if (root->left && !root->left->left && !root->left->right) { // 左子树就是一个左叶子的情况
sum += root->left->val;
}
return sum;
}
};
注意 :
- 注意收集左孩子节点