#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;
}
c++二叉树的创建,遍历合集
最新推荐文章于 2024-08-30 16:00:44 发布