二叉树的建立和遍历

二叉树是一种重要的数据结构,今天花了点时间把二叉树的递归建立和不同的遍历方法用C++实现了

下面是具体的代码


//测试用例abc##de#g##f###   
#include<iostream>
#include<queue>
using namespace std;

typedef struct node{
	char data;
	struct node* lchild;
	struct node* rchild;
}bitree;
bitree *createTree(bitree* root){
	char c;
	cin>>c;
	if(c=='#') root = NULL;
	else{
		root = new bitree;
		root->data = c;
		root->lchild = createTree(root->lchild);
		root->rchild = createTree(root->rchild);
	}
	return root;
}
void inOrder(bitree* root){//中遍历序
	if(!root) return;
	inOrder(root->lchild);
	cout<<root->data;
	inOrder(root->rchild);
}
void preOrder(bitree* root){//先序遍历
	if(!root) return;
	cout<<root->data;
	preOrder(root->lchild);
	preOrder(root->rchild);
}
void postOrder(bitree* root ){//后序遍历
	if(!root) return;
	postOrder(root->lchild);
	postOrder(root->rchild);
	cout<<root->data;
}
void levelOrder(bitree* root){//层次遍历
	queue<bitree*> bitQueue;
	bitQueue.push(root);
	while(!bitQueue.empty()){
		cout<<bitQueue.front()->data<<" ";
		if(bitQueue.front()->lchild) bitQueue.push(bitQueue.front()->lchild);	
		if(bitQueue.front()->rchild) bitQueue.push(bitQueue.front()->rchild);
		bitQueue.pop();
	}
}
int main(){
	bitree* root;
	root = createTree(root);
	preOrder(root);cout<<endl;
	inOrder(root);cout<<endl;
	postOrder(root);cout<<endl;
	levelOrder(root);cout<<endl;
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值