数据结构二叉树的前序中序后序层次遍历简单版,手写

本文介绍了如何实现二叉树的前序、中序、后序遍历以及层次遍历。通过C++代码详细展示了创建二叉树、遍历节点的方法,并提供了层次遍历的队列实现方式。
摘要由CSDN通过智能技术生成
#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") ;
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值