如何使用C++递归来实现在BST(Binary Search Tree)里将所有的叶子节点上的数字求和

小编先翻译什么是BST (Binary Search Tree),对于中文计算机词汇是二叉搜索树,关于这个知识点,小编就不在这里进行解释了,大家还是自行百度吧!或者看看有关数据结构的书就知道了。

那什么情况节点才是属于叶子节点呢?那就是这个节点没有左右两个孩子节点,用代码就是这样子表示:!head->left 和 !head->right

下面就是代码的展示:

//This is the table.h file
#include<iostream>
#include<cctype>
#include<cstring>

using namespace std;

struct node
{
    int data;
    node * left;
    node * right;
};

class table
{
    public:
        //Calculate the sum of every leaf's data (nodes that have no children) in a BST
        int sum_every_leaf();

    private:
        //Calculate the sum of every leaf's data(nodes that have no children) in a BST
        //这个函数是使用递归的
        int sum_every_leaf(node * root);
        node * root;
};

下面是在table.cpp文件里实现这两个函数

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

int table::sum_every_leaf()
{
    return sum_every_leaf(root);
}

int table::sum_every_leaf(node * root)
{
    if(!root)
        return 0;
    if(!root->left && !root->right)
    {
        return root->data + sum_every_leaf(root->left) + sum_every_leaf(root->right);
    }
    return sum_every_leaf(root->left) + sum_every_leaf(root->right);
}

下面是在主函数里进行调用这个函数,我的老师教我们这个也叫做client function

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

int main()
{
    table object;

    int result = object.sum_every_leaf();
    cout<<"The result is: "<<result<<endl;

    return 0;
}

是不是感觉用递归来实现,代码很简洁和简短呢!其实这个用递归的一个特点。说实话,小编都快忘记怎么用循环来实现了。

长话短说,下面是展示结果的截图:
这是结果

小编觉得有可能大家对这个结果看不明白,没事,小编会在白纸上根据这个运行结果来画出这个BST的结构出来,大家一眼就能看的清楚什么回事了。

下面是小编根据结果展示的树结果在纸上画的BST
这是结果
用圆圈圈起来的是叶子节点,然后将这些叶子节点进行求和,就能算出总和是127了。

是不是感觉挺简单的。以后小编还会继续写关于如何用C++递归来实现数据结构中的不同问题,敬请期待吧!

希望这篇文章对大家有所帮助!

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值