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

小编之前写了有关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++递归解决数据结构中的问题,敬请期待吧!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值