110 平衡二叉树
知道返回二叉树两边子树的差,但是代码逻辑不对,错误代码:
int heightree(TreeNode* root)
{
if(root==nullptr)return 0;
int leftheight=heightree(root->left);
int rightheight=heightree(root->right);
return abs(leftheight-rightheight);
}
这里其实是后续遍历,但是处理中间节点的代码逻辑不对,要把每一层的差返回给上一层,如果差太大就返回-1,这样最后返回到最上层也是-1,这样就可以很好的解决子树非平衡二叉树的问题。
class Solution {
public:
int leftheight=0;int rightheight=0;
int heightree(TreeNode* root)
{
if(root==nullptr)return 0;
int leftheight=heightree(root->left);
if(leftheight==-1)return -1;
int rightheight=heightree(root->right);
if(rightheight==-1)return -1;
if(abs(leftheight-rightheight)>1)
return -1;
else return max(leftheight,rightheight)+1;
}
bool isBalanced(TreeNode* root) {
if(root==nullptr)return true;
int i=heightree(root);
if(i==-1)return false;
else return true;
}
};
我认为本题的经典在于返回-1,巧妙地解决了子树的非平衡问题。
257. 二叉树的所有路径
本题用到了回溯算法
class Solution {
public:
void traversal(TreeNode* cur, vector<int>& path, vector<string>& result)
{
path.push_back(cur->val);
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(); // 回溯
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
vector<int> path;
if(root==nullptr)return result;
if (root == NULL) return result;
traversal(root, path, result);
return result;
}
};
404. 左叶子之和
- 本题出大问题,思路也错了,没有正确对左子树进行判断。错误代码:
class Solution {
public:
int sum=0;
int sumOfLeftLeaves(TreeNode* root) {
if(root==nullptr)return 0;
if(root->left==nullptr&&root->right==nullptr)return 0;
sumOfLeftLeaves(root->left);
sum=sum+root->val;
sumOfLeftLeaves(root->right);
return sum+1;
}
};
正确代码:
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(root==nullptr)return 0;
if(root->left==nullptr&&root->right==nullptr)return 0;
int leftValue =sumOfLeftLeaves(root->left);
if (root->left && !root->left->left && !root->left->right)
{
leftValue = root->left->val;//判断是否为左叶子节点
}
int rightValue = sumOfLeftLeaves(root->right); // 右
int sum = leftValue + rightValue;
return sum;
}
};
gpt的代码:
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int sum = 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;
}
};
就是判断左叶子节点出了问题。