1. 程式人生 > >如何用C++遞迴來刪除所有的BST節點

如何用C++遞迴來刪除所有的BST節點

關於BST的知識點,小編不在這裡細講了,不懂的大家自行百度吧或者查詢有關資料。但是,小編還是會告訴你BST的全名是啥,不然你們查資料太費事了。BST的全名是binary search tree。大概中文名就叫做二叉搜尋樹。

下面就展示如何用C++程式碼來實現這道題目

//This is the table.h file
//This file contains the struct and class
//The build function and display functions are always written
#include<iostream>
#include<cstring>
#include<cctype> using namespace std; struct node { int data; node * left; node * right; }; class table { public: //Deallocate all nodes in a BST void deallocate(); private: node * root; //Deallocate all nodes in a BST void deallocate(node *& root); };

下面是如何實現這兩個函數了

//This is the table.cpp file
#include "table.h"

void table::deallocate()
{
    deallocate(root);
}

void table::deallocate(node *& root)
{
    if(!root)
        return;
    deallocate(root->left);
    deallocate(root->right);
    delete root;
    root = NULL;
    return;
}

下面是在主函式裡如何呼叫這兩個函式來測試這兩個函式寫的對不對

//This is the main.cpp file
#include "table.h"

int main()
{
    table object;

    //Deallocate all nodes in a BST
    object.deallocate();

    object.display();

    return 0;
}

是不是感覺這程式碼簡潔明瞭?那現在是展示結果的時候了。關於在主函式裡呼叫了display函式,這個函式是已經寫好的了。

結果展示

關於這個結果,小編還是解釋一下。這個Level 1是表示根節點的位置,而這棵樹的高度是6. 當執行完這個程式碼的時候,這棵樹就變成empty tree了。所以,這就說明這個程式碼寫的是對的。如果哪裡寫的不對或者哪裡不清楚的,就給小編留言吧!歡迎騷擾!

以後小編還會繼續寫有關資料結構的問題,敬請期待吧!