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

如何使用C++递归来实现查找BST(Binary Search Tree)的最大高度

2017-08-15 02:49 363 查看
小编之前写了有关BST的问题的实现,现在还是继续我们的BST的C++递归编程之旅。如果之前没看过小编写的BST的博客,那也没事。现在,小编就实现有关查找最大高度的问题。有关BST的知识点,这里就详细解释了。

直接进入代码环节吧!

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

using namespace std;

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

class table
{
public:
//有关如何建立BST的,小编就不在这里写了
//直接进入如何解决这道题的函数了
//Traverse the tree to determine the height
int height();
private:
//Traverse the tree to determine the height
int height(node * root);
};


下面是table.cpp的文件

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

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

int table::height(node * root)
{
if(!root)
return 0;
int lheight = height(root->left);
int rheight = height(root->right);
if(lheight > rheight)
return lheight + 1;
return rheight + 1;
}


应该很多看了这个代码之后,对为什么return lheight+1 和 return rheight+1产生疑问,没事,小编在这里就给你解释一下,因为树的高度是从根节点开始的,那么由于之前函数进行递归调用时,没有考虑到根节点,所以在后面就得加上数字1,来得出这棵树的最大高度。

下面是在主函数里调用来测试

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

int main()
{
table object;

int result = object.height();
cout<<"The height of this tree is: "<<height<<endl;

return 0;
}


看完这个代码展示,是不是感觉实现这个问题好简单呢!代码简洁,一目了然的感觉。

下面是结果的展示:



有可能一些朋友看不懂这个结果,没事小编为你解答。

上面写的”Inorder traversal” 就是中序遍历,中序遍历就是一个口诀:左根右。

这个”Level 1” 就是根节点的位置。

所以,现在解释应该大家都明白吧!

不明白的话,就留言吧,小编很乐意为你们解答疑问。欢迎骚扰!

小编在接下来还会继续写关于如何用C++递归解决数据结构中的问题,敬请期待吧!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: