二叉树

#define LOCAL
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
typedef char DataType;
typedef struct Node
{
    DataType data;
    struct Node *LChild;
    struct Node *RChild;
}BiTNode,*BiTree;
void Visit(DataType dataType)
{
    cout<<dataType<<" ";
}
void initTree(BiTree *bt)
{
    (*bt)=(BiTNode *)malloc(sizeof(BiTNode));
}
//扩展先序建立二叉树 
void CreateBiTree(BiTree *bt)
{
    DataType ch;    
    ch=getchar();
    if(ch=='.') (*bt)=NULL;
    else
    {
        (*bt)=(BiTree)malloc(sizeof(BiTNode));
        (*bt)->data=ch;
        CreateBiTree(&((*bt)->LChild));    
        CreateBiTree(&((*bt)->RChild));    
    }
}
//先序遍历 
void PreOrder(BiTree root)
{
    if(root!=NULL)
    {
        Visit(root->data);
        PreOrder(root->LChild);
        PreOrder(root->RChild);
    }
} 
//中序遍历 
void InOrder(BiTree root)
{
    if(root!=NULL)
    {
        PreOrder(root->LChild);
        Visit(root->data);
        PreOrder(root->RChild);
    }
}
//后续遍历- 
void PostOrder(BiTree root)
{
    if(root!=NULL)
    {
        PreOrder(root->LChild);
        PreOrder(root->RChild);
        Visit(root->data);        
    }
}
//交换二叉树的左右子树
void change(BiTNode *&root)
{
    BiTree que[maxSize],tmp,q;
    int front=0,rear=0;
    if(root!=NULL)
    {
        rear=(rear+1)%maxSize;
        que[rear]=root;
        while(front!=rear)
        {
            front=(front+1)%maxSize;
            q=que[front];
            if(q->RChild!=NULL)
            {
                rear=(rear+1)%maxSize;
                que[rear]=q->RChild;
            }
            if(q->LChild!=NULL)
            {
                rear=(rear+1)%maxSize;
                que[rear]=q->LChild;
            }
            tmp=q->RChild;
            q->RChild=q->LChild;
            q->LChild=tmp;
        }
    }
}

int main()
{
#ifdef LOCAL
    freopen("data.in","r",stdin);
    freopen("data.out","w",stdout);
#endif   
    BiTree root;
    initTree(&root);
    CreateBiTree(&root);
    PreOrder(root);
    cout<<endl;
    InOrder(root);
    cout<<endl;
    PostOrder(root);
    return 0;
}

二叉树的建立遍历算法。注意输入数据要是一个树的先序遍历的到的一个序列。如:ABD..E..CF..G..

 

posted @ 2014-10-25 19:51  剑风云  阅读(175)  评论(0编辑  收藏  举报