代码随想录第17天| 二叉树4
110. 平衡二叉树(简单)
题目链接:110. 平衡二叉树
代码随想录:110. 平衡二叉树
递归比较左右子树的高度差
class Solution {
public:
int getHeight(TreeNode *root){
if(!root) return 0;
int leftH = getHeight(root->left);
if(leftH == -1) return -1;
int rightH = getHeight(root->right);
if(rightH == -1) return -1;
return abs(leftH - rightH) > 1 ? -1 : 1 + max(leftH, rightH);
}
bool isBalanced(TreeNode* root) {
return getHeight(root) == -1 ? false : true;
}
};
257. 二叉树的所有路径(简单)
LeetCode题目:257. 二叉树的所有路径
代码随想录:257. 二叉树的所有路径
回溯
到叶子节点时收集结果。
class Solution {
public:
vector<string> res;
vector<int> path;
void backtracking(TreeNode* root){
path.push_back(root->val);
if(!root->left && !root->right){
string s;
int i = 0;
for(; i < path.size() - 1; i++){
s += to_string(path[i]);
s += "->";
}
s += to_string(path[i]);
res.push_back(s);
return;
}
if(root->left) {
backtracking(root->left);
path.pop_back();
}
if(root->right) {
backtracking(root->right);
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
if(!root) return res;
backtracking(root);
return res;
}
};
404.左叶子之和 (简单)
LeetCode题目:404.左叶子之和
代码随想录:404.左叶子之和
第一想法:左叶子:root->left && !root->left->left && !root->left->right
sum可以设置为全局变量
class Solution {
public:
int sum = 0;
int sumOfLeftLeaves(TreeNode* root) {
if(root->left && !root->left->left && !root->left->right)
sum += root->left->val;
if(root->left) sumOfLeftLeaves(root->left);
if(root->right) sumOfLeftLeaves(root->right);
return sum;
}
};
文章中解法
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(root == NULL) return 0;
if(!root->left && !root->right) return 0;
int leftVal = sumOfLeftLeaves(root->left);
// 判断是否为左叶子节点需要通过父节点
if(root->left && !root->left->left && !root->left->right)
leftVal = root->left->val;
int rightVal = sumOfLeftLeaves(root->right);
return leftVal + rightVal;
}
};