zoukankan      html  css  js  c++  java
  • 数据结构之二叉树

    #include  "stdafx.h"
    #include<iostream>
    using namespace std;
    #include<malloc.h>
    
    typedef int ElemType;
    typedef struct BiTNode
    {
        ElemType data;    //数据域
        struct BiTNode *lchild;    //左孩子
        struct BiTNode *rchild;     //右孩子
    }BiTNode,*BiTree;
    
    
    //初始化
    void InitBiTree(BiTree &T)
    {
        T=NULL;
    }
    //创建二叉树
    void CreateBiTree(BiTree &T)
    {
      ElemType ch;
      cin>>ch;
      if(ch==-1) /* -1表示空 */
        T=NULL;
      else
      {
        T=(BiTree)malloc(sizeof(BiTNode));
        if(!T)
          exit(OVERFLOW);
        T->data=ch;               /* 生成根结点 */
        CreateBiTree(T->lchild); /* 构造左子树 */
        CreateBiTree(T->rchild); /* 构造右子树 */
      }
    }
    //中序遍历
    void MidVisit(BiTree &T)
    {
        if(T!=NULL)
        {
            MidVisit(T->lchild);
            cout<<T->data;    
            MidVisit(T->rchild);
        }
    }
    
    //前序遍历
    void PreVisit(BiTree &T)
    {
        if(T!=NULL)
        {
            cout<<T->data;    
            MidVisit(T->lchild);
            MidVisit(T->rchild);
        }
    }
    
    //后序遍历
    void PostVisit(BiTree &T)
    {
        if(T!=NULL)
        {
            MidVisit(T->lchild);
            MidVisit(T->rchild);
            cout<<T->data;
        }
    }
    int main(int argc,char* argv[])
    {
        int e;
        BiTree t;
        InitBiTree(t);
        CreateBiTree(t);
        cout<<"前序遍历: ";
        PreVisit(t);cout<<endl;
        cout<<"中序遍历: ";
        MidVisit(t);cout<<endl;
        cout<<"后序遍历: ";
        PostVisit(t);cout<<endl;
        cin>>e;
        return 0;
    }
  • 相关阅读:
    算法 在一个递增的二维数组中查找一个数
    java web----网络编程基础
    java----集合(Map)
    java----集合(List、set)
    java----数组
    java面试----1
    java----NIO
    java----commons-io
    java----文件操作
    爬虫----爬取答案
  • 原文地址:https://www.cnblogs.com/lbangel/p/3333294.html
Copyright © 2011-2022 走看看