关于C++二分搜索树的中序遍历和先序遍历
2015-12-19 22:15
330 查看
这里即将介绍如何对一个二分查找树进行中序遍历和先序遍历进行操作
下面是源代码其中包括自己写的一段建树操作的函数
运行结果如图:
下面是源代码其中包括自己写的一段建树操作的函数
#include<iostream> using namespace std; struct Node { Node *lc; Node *rc; int data; Node(int a) { data = a; lc = NULL; rc = NULL; } }; void built(Node* &root , int a) { if(root == NULL) { root = new Node(a); root->lc = NULL; root->rc = NULL; } else { if(a > root->data) { return built(root->rc , a); } else { return built(root->lc , a); } } } void inorder(Node* root) { if(root != NULL)//即为先对左子树进行遍历,到底后输入在逐步对右子树进行遍历,也可以验证二分搜索树是否有序 { inorder(root->lc); cout << root->data << " "; inorder(root->rc); } } void preorder(Node* root) { if(root != NULL)//先输出根值在对左子树进行遍历,最后对右子树进行遍历 { cout << root->data << " "; preorder(root->lc); preorder(root->rc); } } int main() { int n; cout << "请输入元素数目:"; while(cin >> n && n != 0) { Node *root = NULL; cout << "请输入元素:"; for(int i = 0 ; i < n ; i ++) { int a; cin >> a; built(root,a); } cout << "中序遍历结果为:"; inorder(root); cout << endl; cout << "前序遍历结果为:"; preorder(root); cout << endl << "请输入下一次元素数目,结束请输入'0':"; } cout << endl; return 0; }
运行结果如图:
相关文章推荐
- C++:函数
- c语言常用小知识点(const、sizeof)
- c++中io流的使用
- c++匿名类—指针
- 黑马程序员-C语言-约瑟夫环
- c++静态成员与静态函数
- c++基础语法 构造函数 析构函数 类的组合
- C语言程序设计进阶 第一周1.1笔记
- c语言随机数
- C++中的inline声明
- C++将数值转换为string
- C++ 窗口加载图标
- (解题报告)HDU2024---C语言合法标识符
- 实战c++中的vector系列--正确释放vector的内存(clear(), swap(), shrink_to_fit())
- 实战c++中的vector系列--正确释放vector的内存(clear(), swap(), shrink_to_fit())
- 第一次写自己的blog--C语言基础题目--字母螺旋方阵
- c++/c内部调用TCL
- C语言回顾 学习进程
- C++中的头文件和源文件
- C++连接数据库