#include<iostream>
#include<windows.h>
#include<queue>
using namespace std;
struct BinTreeNode{
char data ;
BinTreeNode *left ;
BinTreeNode *right ;
};
//BinTree 类里所要书写的函数只有create,前中后序的遍历,所谓的visit函数
class BinTree{
public:
//******************************************************//
void create(BinTreeNode *&t){//创建一颗树
char c ;
cin >> c;
if (c == '#'){
t = NULL ;
}
else{
t = new BinTreeNode ;
t->data = c ;
create( t->left ) ;
create( t->right ) ;
}
}
//******************************************************//
void visit (BinTreeNode *&t) {//书上对visit函数的书写没有明确指明,其实visit函数就是找到结点,然后进行某个操作
if(t != NULL) { cout<<t->data ; }
}
void Pre(BinTreeNode *&t){// 前
if (t != NULL) {
visit( t ) ;
Pre( t->left ) ;
Pre( t->right ) ;
}
}
void In(BinTreeNode *&t){// 中
if (t != NULL) {
In( t->left ) ;
visit( t ) ;
In( t->right ) ;
}
}
void Post(BinTreeNode *&t){// 后
if (t != NULL) {
Post ( t->left ) ;
Post ( t->right ) ;
visit ( t ) ;
}
}
void Level( BinTreeNode *&t) { //层次遍历要用到队列,个人感觉不用队列用数组应该也是行的,但是用数组有点难......
BinTreeNode *p = t ;
queue<BinTreeNode*> test ;
test.push ( p ) ;//让root结点进去队
while(!test.empty()) {
p = test.front () ;//让p指向队列的顶
cout<<p->data ;
test.pop () ; //输出后就把它弹出来
if(p->left != NULL) {
test.push( p->left ) ;// 不为空就把他放进去,然后用while循环一个个弹出来
}
if(p->right != NULL) {
test.push ( p->right ) ;
}
}
}//用队列不用栈的原因是栈是先进后出,队列是先进先出,可以自己在画个图看看
};
/*********************************************
我希望各位能专心看里面的各种类型,为什么会用到*,我写的时候卡了好久..
**********************************************/
int main() {
BinTreeNode *test;
BinTree check ;
cout<<"input the tree : ";
check.create ( test ) ;
cout<<"Pre : ";
check.Pre( test ) ;
cout<<endl;
cout<<"In : ";
check.In ( test ) ;
cout<<endl;
cout<<"Post : ";
check.Post ( test ) ;
cout<<endl;
cout<<"Level : " ;
check.Level( test ) ;
cout<<endl;
system("pause") ;
}
数据结构二叉树的前序中序后序层次遍历简单版,手写
最新推荐文章于 2024-07-16 16:23:19 发布
本文介绍了如何实现二叉树的前序、中序、后序遍历以及层次遍历。通过C++代码详细展示了创建二叉树、遍历节点的方法,并提供了层次遍历的队列实现方式。
摘要由CSDN通过智能技术生成