c++实现二叉搜索树
来源:互联网 发布:物业管理系统源码 编辑:程序博客网 时间:2024/05/22 13:06
自己实现了一下二叉搜索树的数据结构,记录一下:
#include <iostream>using namespace std;struct TreeNode{ int val; TreeNode *left; TreeNode *right; TreeNode(int value) { val=value; left=NULL; right=NULL; }};class SearchTree{public: SearchTree(); ~SearchTree(); void Destory(TreeNode *); void Insertnode(int); void Preorder(TreeNode *); void Inorder(TreeNode *); void Postorder(TreeNode *); void Predisplay(); void Indisplay(); void Postdisplay();private: TreeNode *root;};SearchTree::SearchTree(){ root=NULL;}SearchTree::~SearchTree(){ cout<<"析构二叉搜索树:"<<endl; Destory(root);}void SearchTree::Destory(TreeNode *node){ if(node!=NULL) { Destory(node->left); Destory(node->right); cout<<node->val<<" "; delete node; }}void SearchTree::Insertnode(int value){ if(root==NULL) root=new TreeNode(value); else { TreeNode *p,*pre; pre=p=root; while(p) { if(p->val==value) return; else if(p->val>value) { pre=p; p=p->left; } else { pre=p; p=p->right; } } p=new TreeNode(value); if(pre->val>value) pre->left=p; else pre->right=p; }}void SearchTree::Predisplay(){ Preorder(root);}void SearchTree::Preorder(TreeNode *root){ if(root) { cout<<root->val<<" "; Preorder(root->left); Preorder(root->right); }}void SearchTree::Indisplay(){ Inorder(root);}void SearchTree::Inorder(TreeNode *root){ if(root) { Inorder(root->left); cout<<root->val<<" "; Inorder(root->right); }}void SearchTree::Postdisplay(){ Postorder(root);}void SearchTree::Postorder(TreeNode *root){ if(root) { Postorder(root->left); Postorder(root->right); cout<<root->val<<" "; }}int main(){ SearchTree t; int a[]={7,4,2,3,15,35,6,45,55,20,1,14}; int n=sizeof(a)/sizeof(a[0]); cout<<"构造二叉搜索树:"<<endl; for(int i=0;i<n;++i) { cout<<a[i]<<" "; t.Insertnode(a[i]); } cout<<endl<<"先序遍历序列: "<<endl; t.Predisplay(); cout<<endl<<"中序遍历序列: "<<endl; t.Indisplay(); cout<<endl<<"后序遍历序列: "<<endl; t.Postdisplay(); cout<<endl; return 0;}
0 0
- [C++] 实现二叉搜索树
- 二叉搜索树 c 语言实现
- 二叉搜索树 C语言实现
- 【C基础】二叉搜索树的实现
- 二叉搜索树(c实现)
- 【C++】实现的二叉搜索树BST
- c语言实现:二叉搜索树
- c语言二叉树和二叉搜索树的实现
- 二叉搜索树(c++)
- 二叉搜索树实现文件C语言(BinarySearchTree.c)
- 二叉搜索树实现
- 搜索二叉树实现
- 搜索二叉树实现
- 二叉搜索树实现
- 3.16(c程序实现)特殊的平衡二叉搜索树之完全二叉搜索树
- 二叉搜索树的基本操作(C代码实现)
- C语言二叉树实现及搜索算法
- 二叉树的创建、遍历及搜索(C实现)
- .net自定义控件(一)
- 解决opensips启动时报ERROR:uri:db_checks_fixup1: configuration error 错误
- .net自定义控件(二)
- 倒置函数reverse
- 解决opensips启动时出现PID file /var/run/opensips.pid does not exist 的错误
- c++实现二叉搜索树
- 我的网站终于上线了
- Flash ANE打包
- .net自定义控件(三)
- sort函数降序排序
- nutch-1.4在eclipse中运行
- 世界杯,考试,人
- 安装OpenFire时出现HTTP ERROR 500问题的解决
- 深刻理解Linux进程间通信(IPC)