이 튜토리얼에서는 delete 키워드를 사용하여 바이너리 트리를 삭제하는 방법을 배울 것입니다.
이진을 삭제하기 위해 소멸자 멤버 함수를 사용할 것입니다. 소멸자 멤버 함수는 객체가 범위를 벗어나거나 삭제를 호출하여 소멸될 때 자동으로 호출됩니다.
소멸자 멤버 함수는 물결표(~)가 있는 클래스 이름을 가집니다. 그 전에.
문제를 해결하는 단계를 살펴보겠습니다.
-
Node라는 클래스를 작성하십시오.
-
노드에 대한 데이터를 받는 생성자 함수를 작성하십시오.
-
소멸자 함수를 작성하십시오.
-
왼쪽 노드를 삭제합니다.
-
오른쪽 노드를 삭제합니다.
-
현재 노드 데이터를 인쇄합니다.
-
-
더미 데이터로 바이너리 트리를 초기화합니다.
-
루트 삭제를 사용하여 바이너리 트레스를 삭제합니다. 성명서.
예
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
// constructor
Node(int data) {
this->data = data;
this->left = NULL;
this->right = NULL;
}
// destructor
~Node() {
// deleting the left and right pointers
delete left;
delete right;
// printing node data
cout << "Deleted node with data " << this->data << endl;
}
};
int main() {
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
// deleting the entire tree using destructure function
delete root;
return 0;
} 출력
위의 프로그램을 실행하면 다음과 같은 결과를 얻을 수 있습니다.
Deleted node with data 4 Deleted node with data 5 Deleted node with data 2 Deleted node with data 6 Deleted node with data 7 Deleted node with data 3 Deleted node with data 1
결론
튜토리얼에서 질문이 있는 경우 댓글 섹션에 언급하세요.