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

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值