第五题:实现由中序序列和后序序列建立一棵二叉树,并实现非递归先序遍历。

 非递归先序遍历算法思想:

使用一个栈存放结点类的指针,用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;
}

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值