c++二叉树的创建,遍历合集

#include<iostream>
#include<vector>
#include<string>
#include<stack>
#include<queue>
#include<cctype>
using namespace std;
struct treeNode{
	string data;
	treeNode *left;
	treeNode *right;
	treeNode(string v):data(v),left(NULL),right(NULL){}
};

//建立二叉树 
treeNode* build2(treeNode *t)
{
	string x;
	cin>>x;
	if(x=="!") return NULL;
	else{
		t = new treeNode(x);
		t->left= build2(t->left);
		t->right =  build2(t->right);
	}
	return t;
}

//递归建立二叉排序树
treeNode* build(treeNode* t,string v)
{
	if(t==NULL){
		t = new treeNode(v);
		return t;
	}
	if(v<t->data) t->left = build(t->left,v);
	else if(v>t->data) t->right=build(t->right,v);
	return t;
}

//递归遍历 
void travel(treeNode *t,vector<string>&v)
{
	if(t==NULL) return;
	travel(t->left,v);
	v.push_back(t->data);
	travel(t->right,v);
}

//循环前序遍历
void travel2(treeNode *t,vector<string>&v)
{
	stack<treeNode*> st;
	if(t==NULL) return ;
	st.push(t);
	while(!st.empty()){
		treeNode *n = st.top();
		st.pop();
		v.push_back(n->data);
		if(t->right!=NULL) st.push(t->right);
		if(t->left!=NULL) st.push(t->left);
	}
 }
 
 //循环中序遍历
void travel3(treeNode *t,vector<string>&v)
{
 	stack<treeNode*> st;
 	if(t==NULL) return;
 	st.push(t);
 	treeNode *n =t;
 	while(!st.empty()||n!=NULL){
 		if(n!=NULL){
 			st.push(n);
 			n = n->left;
		 } 
		 else{
		 	n = st.top();
		 	st.pop();
		 	v.push_back(n->data);
		 	n = n->right;
		 }
	 }
} 

//循环后序遍历 
void travel3(treeNode *t,vector<string> &v)
{
	stack<treeNode*> st;
	if(t==NULL) return;
	st.push(t);
	while(!st.emplace()){
		treeNode *n = st.top();
		st.pop();
		v.push_bck(n->data);
		if(n->left) st.push(t->left);
		if(n->right) st.push(t->right);
	}
}

//层序遍历
void  leveltravel(treeNode *t,vector<string>&s)
{
	queue<treeNode*> q;
	if(t!=NULL) q.push(t);
	while(!q.empty()){
		treeNode *n = q.front();
		q.pop();
		s.push_back(n->data);
		if(n->left!=NULL) q.push(n->left);
		if(n->right!=NULL) q.push(n->right);
	}
}

int main()
{
	treeNode* t =NULL;
	vector<string> res;
	string num[]={"B","D","C","A","F"};
	for(int i=0;i<5;i++) t=build(t,num[i]);
	leveltravel(t,res);
	for(int i=0;i<res.size();i++) cout << res[i]<<" ";
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值