使用C++程式中的delete關鍵字刪除二叉樹


在本教程中,我們將學習如何使用delete關鍵字刪除二叉樹。

我們將使用解構函式來刪除二叉樹。當物件超出作用域或透過呼叫delete被銷燬時,會自動呼叫解構函式。

解構函式的名稱與類名相同,但在前面加有波浪號 (~)

讓我們看看解決這個問題的步驟。

  • 編寫一個名為Node的類。

  • 編寫一個接受節點資料的建構函式。

  • 編寫一個解構函式。

    • 刪除左子節點。

    • 刪除右子節點。

    • 列印當前節點資料。

  • 使用虛擬資料初始化二叉樹。

  • 使用delete root語句刪除二叉樹。

示例

 線上演示

#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

結論

如果您在本教程中有任何疑問,請在評論區提出。

更新於:2021年1月27日

2K+ 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.