gpt4 book ai didi

c++ - 如何删除 BST 的所有节点以便在 C++ 中重用

转载 作者:行者123 更新时间:2023-11-30 05:23:16 24 4
gpt4 key购买 nike

我无法删除 BST 的所有节点以供重用。对于第一组输入,我的代码工作正常但后来的输入失败。我在谷歌上搜索了很多,但找不到与我的问题相关的任何解决方案。为了澄清起见,我粘贴了我的完整源代码。我发现以前在这里问过这种问题 How to delete all nodes of a Binary Search Tree我不太了解python。为此,这里再次询问了这个话题。

    #include<bits/stdc++.h>
using namespace std;
int size,c=0;
struct BstNode {
int data;
BstNode* left;
BstNode* right;
};

BstNode* insert(BstNode* root,int data) {
if(root==NULL) {
root=new BstNode();
root->data=data;
root->left=root->right=NULL;
}
else if(data<root->data) {
root->left=insert(root->left,data);
}
else {
root->right=insert(root->right,data);
}
return root;
}

void preorderTraversal(BstNode* root) {
if(root!=NULL) {

c++;
if(c==size) cout<<root->data<<endl;
else cout<<root->data<<" ";
preorderTraversal(root->left);
preorderTraversal(root->right);
}
}

void inorderTraversal(BstNode* root) {
if(root!=NULL) {
inorderTraversal(root->left);
c++;
if(c==size) cout<<root->data<<endl;
else cout<<root->data<<" ";
inorderTraversal(root->right);
}
}

void postorderTraversal(BstNode* root) {
if(root!=NULL) {
postorderTraversal(root->left);
postorderTraversal(root->right);
c++;
if(c==size) cout<<root->data<<endl;
else cout<<root->data<<" ";
}
}

void deletepostorderTraversal(BstNode* root) {
if(root!=NULL) {
deletepostorderTraversal(root->left);
deletepostorderTraversal(root->right);
delete root;
}
}

int main() {
int test_case;
while(cin>>test_case) {
cin>>size;
BstNode* root=NULL; //create the root
for(int i=0;i<size;i++) {
int data;cin>>data;
root=insert(root,data);
}
c=0;
cout<<"Pre.: ";
preorderTraversal(root);
cout<<"In..: ";
c=0;
inorderTraversal(root);
cout<<"Post: ";
c=0;
postorderTraversal(root);
cout<<endl;
deletepostorderTraversal(root); //delete all the nodes
//i can't reuse this code again.
// root=NULL;
// if(root==NULL) cout<<"Deleted"<<endl;
}
}

最佳答案

通过引用传递root,并在删除完成后将其设置为NULL:

void deletepostorderTraversal(BstNode*& root) {
// ^
if(root!=NULL) {
deletepostorderTraversal(root->left);
deletepostorderTraversal(root->right);
delete root;
root = NULL; // <<<<<<<<<<<<<<<<
}
}

在您的版本中,指针将按值传递,并且在函数内部对其所做的更改永远不会出现在函数范围之外。

使用如上所示的签名,并在函数内将 root 设置为 NULL 您可以再次(重新)使用 insert()在调用 deletepostorderTraversal() 后将 root 节点设置为 NULL

参见 Live Demo

关于c++ - 如何删除 BST 的所有节点以便在 C++ 中重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39277918/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com