如何用C++递归来删除所有的BST节点

来源:互联网 发布:全站仪传输软件使用 编辑:程序博客网 时间:2024/06/07 04:06

关于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了。所以,这就说明这个代码写的是对的。如果哪里写的不对或者哪里不清楚的,就给小编留言吧!欢迎骚扰!

以后小编还会继续写有关数据结构的问题,敬请期待吧!

阅读全文
1 0
原创粉丝点击