Open youngyangyang04 opened 3 months ago
class Solution {
public TreeNode trimBST(TreeNode node, int low, int high) {
if(node == null) return null;
if(node.val < low){
return trimBST(node.right, low, high); // 返回右子树
}
if(node.val > high){
return trimBST(node.left, low, high); // 返回左子树
}
node.left = trimBST(node.left, low, high); // 修剪右子树
node.right = trimBST(node.right, low, high); // 修剪右子树
return node;
}
}
// root.val > high 和 root.val < low 的时候不直接return,而是让root等于,对于我自己来说更好理解一些
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
if (root == null) return root;
if (root.val > high) {
root = trimBST(root.left, low, high);
}
else if (root.val < low) {
root = trimBST(root.right, low, high);
}
else {
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
}
return root;
}
}
佬们,为什么这样会报错啊 class Solution { public: TreeNode trimBST(TreeNode root, int low, int high) { if(root->val>=low&&root->val<=high) { if(root->left!=nullptr) root->left = trimBST(root->left, low, high); if(root->right!=nullptr) root->right = trimBST(root->right, low, high); } else { if(root->left==nullptr&&root->right==nullptr) root = nullptr; else if(root->left!=nullptr&&root->right==nullptr) root = trimBST(root->left, low, high); else if(root->left==nullptr&&root->right!=nullptr) root = trimBST(root->right, low, high); else { TreeNode* node = root->right; node = root->right; while(node->left!=nullptr) node = node->left; node->left = trimBST(root->left, low, high); root = trimBST(root->right, low, high); } } return root; } };
@gWeiXP
佬们,为什么这样会报错啊 class Solution { public: TreeNode trimBST(TreeNode root, int low, int high) { if(root->val>=low&&root->val<=high) { if(root->left!=nullptr) root->left = trimBST(root->left, low, high); if(root->right!=nullptr) root->right = trimBST(root->right, low, high); } else { if(root->left==nullptr&&root->right==nullptr) root = nullptr; else if(root->left!=nullptr&&root->right==nullptr) root = trimBST(root->left, low, high); else if(root->left==nullptr&&root->right!=nullptr) root = trimBST(root->right, low, high); else { TreeNode* node = root->right; node = root->right; while(node->left!=nullptr) node = node->left; node->left = trimBST(root->left, low, high); root = trimBST(root->right, low, high); } } return root; } };
我认为是最外层的else逻辑中,对于指针的错误使用导致的内存泄漏或者数据破坏。因为我不是写c++的,所以并不是很懂,仅供参考,其实可以去问GPT
为什么这道题的C++版本没有手动释放删除节点的内存呢?
https://www.programmercarl.com/0669.%E4%BF%AE%E5%89%AA%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91.html