小编先翻译什么是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++递归来实现数据结构中的不同问题,敬请期待吧!
希望这篇文章对大家有所帮助!