非递归先序遍历算法思想:
使用一个栈存放结点类的指针,用while语句;
当栈非空或者当前指针(初始为root)非空时,进入循环;
如果指针非空,访问;然后判断当前指针的右孩子是否为空,如果不为空则入栈;当前指针指向其右孩子;
如果指针为空且栈不为空,当前指针指向栈顶元素;
#include<iostream>
#include<cstring>
#include<stack>
#include<queue>
using namespace std;
queue<char> target;
stack<char> post;
template<class T>
class BinarytreeNode
{
public:
T data;
BinarytreeNode<T> *leftchild;
BinarytreeNode<T> *rightchild;
BinarytreeNode(T data = 0){
this->data = data;
this->leftchild = NULL;
this->rightchild = NULL;
}
};
template<class T>
class Binarytree{
private:
BinarytreeNode<T> *root;
public:
Binarytree(BinarytreeNode<T> *root = NULL){
this->root = root;
}
void visit(BinarytreeNode<T> *root){
cout << root->data << " ";
}
BinarytreeNode<T>* Create(); //创建链表
void preOrder(BinarytreeNode<T> *root); //先序遍历
void transf(); //将后序和中序序列转换成带标记的序列
};
template<class T>
void Binarytree<T> :: transf(){
string in;
cout << "请输入中序序列:" << endl;
cin >> in;
cout << "请输入后序序列(输入0截止):" << endl;
int i;
char x;
cin >> x;
while(x != '0'){
post.push(x);
cin >> x;
}
while(!post.empty()){
x = post.top();
post.pop();
target.push(x);
i = in.find(x);
in[i] = '#';
if(i == 0)
target.push('#');
if(i == in.length()-1)
target.push('#');
if(i>=1 && in[i-1]=='#')
target.push('#');
if(i<in.length()-1&&in[i+1]=='#')
target.push('#');
}
}
template<class T>
BinarytreeNode<T>* Binarytree<T> :: Create(){
char x;
if(!target.empty()){
x = target.front();
target.pop();
}
if(x == '#')
return NULL;
else{
BinarytreeNode<T> *p = new BinarytreeNode<T>(x);
p->rightchild = Create();
p->leftchild = Create();
return p;
}
}
template<class T>
void Binarytree<T> :: preOrder(BinarytreeNode<T> *root){
using std :: stack;
stack<BinarytreeNode<char>* > st;
while(root!=NULL || !st.empty()){
if(root !=NULL){
visit(root);
st.push(root->rightchild);
root = root->leftchild;
}
else{
root = st.top();
st.pop();
}
}
}
int main(){
cout << "先序:abdfgceh 中序:bfdgaceh 后序:fgdbheca" << endl << endl << endl;
Binarytree<char> *t;
BinarytreeNode<char> *root;
t->transf();
root = t->Create();
cout << "二叉树先序序列为:" << endl;
t->preOrder(root);
return 0;
}