如何使用C++递归来实现查找BST(Binary Search Tree)的最大高度
来源:互联网 发布:程序员的数学pdf百度云 编辑:程序博客网 时间:2024/05/23 18:50
小编之前写了有关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 0
- 如何使用C++递归来实现查找BST(Binary Search Tree)的最大高度
- 如何使用C++递归来实现在BST(Binary Search Tree)里将所有的叶子节点上的数字求和
- BST(Binary Search Tree,二叉查找树,二叉排序树)c的实现(部分函数不知如何调用)
- 二分查找树的C++实现 Binary Search Tree(BST)
- BST(Binary Search Tree) 二叉查找树
- 二叉排序树/二叉查找树 (binary sort tree/ binary search tree)的C语言实现
- Binary Search Tree (BST)
- Binary Search Tree (BST)
- 高度最小的BST&&108. Convert Sorted Array to Binary Search Tree
- 二叉搜索树(Binary Search Tree)的递归和非递归代码实现(C++)
- 二叉搜索树(Binary Search Tree)的递归和非递归代码实现(C++)
- 二叉查找树(binary search tree (BST))--算法导论示例
- BST(Binary Search Tree 二叉查找树模版)
- BST(binary search tree)
- 数据结构-BST(Binary Search Tree)
- 浅谈BST (Binary Search Tree)
- BST-----Validate Binary Search Tree
- [数据结构]10.2实现binary search tree的查找和插入操作,用非递归的方法实现
- Vim常用命令集合
- vi使用方法总结
- uva116单向TSP 多段图dp
- codeforces 839A 428 Div2 B Game of the Rows
- 做好产品需要了解哪些呢?
- 如何使用C++递归来实现查找BST(Binary Search Tree)的最大高度
- 异常1
- 异常2
- PAT 1008. 数组元素循环右移问题 (技巧解法,后续会补充非技巧解法)
- 包
- codeforces 839C Div428B Journey
- 【云服务器】安装SSL证书,使用HTTPS协议
- jar打包
- Arishmoon Tony的高考素材本.1