二叉树的遍历
2015-06-17 20:59
381 查看
所谓二叉树的遍历无非是三种,先序遍历,中序遍历,后序遍历,而此间的先中后指明的都是根的所在,其他都是先左子树,而后右子树
也即先序遍历:根 左子树 右子树
中序遍历:左子树 根 右子树
后序遍历:左子树 右子树 根
也即先序遍历:根 左子树 右子树
中序遍历:左子树 根 右子树
后序遍历:左子树 右子树 根
#include<iostream> using namespace std; struct node{ node(){ value = -1; left = NULL; right = NULL; } int value; node* left; node* right; }; static node* head = NULL; void insert_node(int value) { if (value == -1) { return; } if (NULL == head) { head = new node(); head->value = value; } else { node* tmp = head; while (tmp != NULL) { if (tmp->value > value) { //value应该在tmp的右子树上 if (NULL == tmp->right) { tmp->right = new node(); tmp->right->value = value; break; } else { tmp = tmp->right; } } else { if (NULL == tmp->left) { tmp->left = new node(); tmp->left->value = value; break; } else { tmp = tmp->left; } } } } } void pre_itera(node* mm) { if (NULL == mm) { return; } cout << mm->value << endl; pre_itera(mm->left); pre_itera(mm->right); } void getMax_Min(node*mm,int& max,int& min) { if (NULL != mm) { if (mm->value > max) { max = mm->value; } if (mm->value < min) { min = mm->value; } getMax_Min(mm->left, max, min); getMax_Min(mm->right, max, min); } } void mid_itera(node* mm) { if (NULL!= mm) { mid_itera(mm->left); cout << mm->value << endl; mid_itera(mm->right); } } void aft_itera(node* mm) { if (NULL == mm) { return; } aft_itera(mm->left); aft_itera(mm->right); cout << mm->value << endl; } int main() { int a[6] = { 10, 12, 5, 13, 11, 6 }; int i = 0; while (i!=6) { insert_node(a[i++]); } cout << "先序遍历结果:\n"; pre_itera(head); cout << "中序遍历结果:\n"; mid_itera(head); cout << "后序遍历结果:\n"; aft_itera(head); cout << "获得树中最大值和最小值:\n"; int max=a[0], min=a[0]; getMax_Min(head, max, min); cout << "最大值是:"<<max<<endl; cout << "最小值是:" << min; }而对于最大最小值的获取无非是进行整个二叉树的遍历,将最大值,最小值设置为数组中的第一个元素即可,便利过程中一次比较,记录下最大最小值即可
相关文章推荐
- SSRS 指定数据行数进行换页
- C#下AxShockwaveFlash的成员函数
- SQL中的循环:while 1
- Best Time to Buy and Sell Stock IV
- [转]100个经典C语言程序(益智类问题)
- FR报表 FileName
- C++ Primer第一章(submit 转换格式)
- [Objective-C] 007_Foundation框架之NSString与NSMutableString
- leetcode[67]:Add Binary
- Android/Java线程同步
- cef运行时间太久的问题跟进
- linux下core文件调试方法
- php array_walk函数的用法
- jdk1.7版本的安装和配置
- 返回一个二维整数数组中最大联通子数组的和
- 结对开发之最联通子数组
- javaScript一些函数--Math()
- JAVA反射机制
- Algs4-2.2.2 归并算法为EASYQUESTION排序的轨迹
- 文章标题