바이너리 트리에서 가장 큰 숫자를 탐지하기 위해 작은 코드를 작성 했으므로 간단하고 잘 작동하며 마지막 오른쪽 노드 (경우에 따라)까지 멀리 이동 한 다음 나는 이걸 삭제하고 싶다. 나는 비슷한 물음으로 보았지만 숫자 만 지워야한다. 그러나 검색을 마치고 돌아 오면 내 prog이 충돌한다. 삭제하고 다시 나열하십시오.바이너리 트리 오류에서 삭제
다음T Remove(Node* theRoot)
{
if (root == NULL)
{
cout<<"There is no tree";
return -1;
}
if (theRoot->rChildptr != NULL)
return Largest(theRoot->rChildptr);
else
delete theRoot;
return theRoot->data;
}
전체 코드입니다 :
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
template<class T>
class BinaryTree
{
struct Node
{
T data;
Node* lChildptr;
Node* rChildptr;
Node(T dataNew)
{
data = dataNew;
lChildptr = NULL;
rChildptr = NULL;
}
};
private:
Node* root;
void Insert(T newData, Node* &theRoot)
{
if(theRoot == NULL)
{
theRoot = new Node(newData);
return;
}
if(newData < theRoot->data)
Insert(newData, theRoot->lChildptr);
else
Insert(newData, theRoot->rChildptr);
}
void PrintTree(Node* theRoot)
{
if(theRoot != NULL)
{
PrintTree(theRoot->lChildptr);
cout<< theRoot->data<<" \n";
PrintTree(theRoot->rChildptr);
}
}
T Largest(Node* theRoot)
{
if (root == NULL)
{
cout<<"There is no tree";
return -1;
}
if (theRoot->rChildptr != NULL)
return Largest(theRoot->rChildptr);
else
delete theRoot;
return theRoot->data;
}
T Remove(Node* theRoot)
{
if (root == NULL)
{
cout<<"There is no tree";
return -1;
}
if (theRoot->rChildptr != NULL)
return Largest(theRoot->rChildptr);
else
delete theRoot;
return ;
};
public:
BinaryTree()
{
root = NULL;
}
void AddItem(T newData)
{
Insert(newData, root);
}
void PrintTree()
{
PrintTree(root);
}
T Largest()
{
return Largest(root);
}
//void Remove()
//{
// Remove(root);
//}
};
int main()
{
BinaryTree<int> *myBT = new BinaryTree<int>();
myBT->AddItem(2);
myBT->AddItem(20);
myBT->AddItem(5);
myBT->AddItem(1);
myBT->AddItem(10);
myBT->AddItem(15);
//for(int i = 0; i < 10; i++) //randommal tolti fel
//myBT->AddItem(rand() % 100);
cout << "BinaryTree:" << endl; //kilistazaa a fat
myBT->PrintTree();
cout << "Largest element: " << myBT->Largest() << endl; //visszaadja a legnagyobb elemet
//myBT->Remove();
myBT->PrintTree();
}
실제 삭제 기능은 그래서는 음식물을 실행할 수 있습니다 // 주석에
여기 내 검색입니다.
whats delete? u는 null 객체에 대한 데이터를 호출하지 않는다고 확신합니까? –
확실하지 않지만, 물결 모양의 비슷한 질문을하고 거의 모든 경우에 노드를 없애기 위해 googeld를 사용했습니다. –
보이지 않습니까? 당신이 루트를 지웠을 때 아무 것도 지적하지 않았습니다. – nullpotent