zoukankan      html  css  js  c++  java
  • 二叉树

    #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..

     

  • 相关阅读:
    poj3083(Children of the Candy Corn)
    poj3278(Catch That Cow)
    poj2996(Help Me with the Game)
    poj2993(Emag eht htiw Em Pleh)
    js 对多sheet Excel赋值操作
    学习进度总结(三)
    学习进度总结(二)
    学习进度总结(一)
    《人月神话》阅读笔记(1)
    Android studio的安装与使用
  • 原文地址:https://www.cnblogs.com/jianfengyun/p/4050776.html
Copyright © 2011-2022 走看看