您的位置:首页 > 编程语言 > C语言/C++

如何用C++递归在BST(Binary Search Tree) 数有几个节点大于根节点的数字

2017-08-13 16:07 295 查看
小编上课时使用英文教材,所以对中文计算机词汇不是那么了解,所以,这里先表示抱歉。但是,我还是尽量使用中文计算机词汇来表达,这样有助于你们能看的懂小编在写什么。

现在,要实现在Binary Search Tree, 也就是二叉搜索树。下面小编就用BST来表示二叉搜索树,因为这样方便。关于知识点,小编就不在写了,不懂得就百度吧!

OK,现在就展示如何用C++递归来实现这个问题。

//Function prototype是写在.h文件
struct node
{
int data;
node * left;
node * right;
};

class table
{
public:
//Count the number of nodes with data greater than the root's data in a BST
int count_greater_root();

private:
//Count the number of nodes with data greater than the root's data in a BST
//这个是专门用递归来实现的
//也叫做recursive function
int count_greater_root(node * root, int num);
};

//下面一部分是来实现这两个函数的
//实现函数在.cpp文件里
int table::count_greater_root()
{
return count_greater_root(root,root->data);
}

int table::count_greater_root(node * root, int num)
{
if(!root)
return 0;
if(root->data > num)
{
return count_greater_root(root->right,num)+count_greater_root(root->left,num) + 1;
}
return count_greater_root(root->left,num)+count_greater_root(root->right,num);
}

//下面是在主函数里进行调用这些函数
//主函数也是写在.cpp文件里的
int main()
{
table object;
int result = object.count_greater_root();
cout<<"The result is: "<<result<<endl;

return 0;
}


下面是展示运行结果:



有可能大家对这个结果看不懂,没事小编会接触你们的疑惑的。

下面展示的是小编在白纸上根据结果的展示来描述这个BST.



所以,根据这个树的形状,就可以知道比数字21大的数字一共有8个。

希望这篇文章对大家有所帮助,以后,小编还会继续写有关BST的C++递归博客送给大家。敬请期待吧!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: