二叉树的序遍历

递归和非递归的深度遍历;


采用了重定向;当前路径下需要一个tree.txt

内容为

ABDG##H###CE##FI###

注释中也有,文本内容用做树的建立

测试树的形态应该是:



#include<iostream>
#include<ctime>
#include<cstdio>
using namespace std;

typedef struct Node{
    char data;
    struct Node *left , *right;
}Node;
Node* s[100];
void Pre_Create(Node*& root){// ABDG##H###CE##FI###
    char t;
    cin>>t;
    if(t=='#')
        root=NULL;
    else {
        root = new Node;
        root->data = t;
        Pre_Create(root->left);
        Pre_Create(root->right);
    }
}
void PreOrder(Node*root){
    if(!root) return;
    cout<<root->data;
    PreOrder(root->left);
    PreOrder(root->right);
}
void PreOrder_s(Node*p){
    int ap=0;
    Node* q;
    while(p||ap){
        if(p){
            cout<<p->data;
            s[++ap]=p;
            p=p->left;
        }else {
            q=s[ap--];
            p=q->right;
        }
    }

}

void InOrder(Node*root){
    if(!root) return;
    InOrder(root->left);
    cout<<root->data;
    InOrder(root->right);
}
void InOrder_s(Node*p){
    int ap=0;
    Node* q;
    while(p||ap){
        if(p){
            s[++ap]=p;
            p=p->left;
        }else {
            q=s[ap--];
            cout<<q->data;
            p=q->right;
        }
    }

}
void PosOrder(Node*root){
    if(!root) return;
    PosOrder(root->left);
    PosOrder(root->right);
    cout<<root->data;
}
void PosOrder_s(Node*p){
    int ap=0;
    int flag[100];
    Node*q;
    while(p||ap){
        if(p){
            s[++ap] = p;
            flag[ap]= 0;
            p=p->left;
        }else {
            q = s[ap];
            if(flag[ap]==0){
                p=q->right;
                flag[ap]=1;
            }else {
                cout<<q->data;
                ap--;
            }
        }
    }
}


int main(){
    Node*root;
    freopen(".\\tree.txt","r",stdin);
    Pre_Create(root);
    cout<<"PreOrder:"<<endl;
    PreOrder(root);
    cout<<endl;
    PreOrder_s(root);
    cout<<endl;

    cout<<"InOrder:"<<endl;
    InOrder(root);
    cout<<endl;
    InOrder_s(root);
    cout<<endl;

     cout<<"PosOrder:"<<endl;
    PosOrder(root);
    cout<<endl;
    PosOrder_s(root);

    cout<<"\n\nTimeLimit:"<<((double)clock()/CLOCKS_PER_SEC)<<endl;
    return 0;
}


你可能感兴趣的:(递归,二叉树,遍历,非递归,先序,前序)