zoukankan      html  css  js  c++  java
  • 问题 A: 二叉排序树

    题目描述

    输入一系列整数,建立二叉排序数,并进行前序,中序,后序遍历。

    输入

    输入第一行包括一个整数n(1<=n<=100)。接下来的一行包括n个整数。

    输出

    可能有多组测试数据,对于每组数据,将题目所给数据建立一个二叉排序树,并对二叉排序树进行前序、中序和后序遍历。每种遍历结果输出一行。每行最后一个数据之后有一个空格。

    样例输入 Copy

    1
    2 
    2
    8 15 
    4
    21 10 5 39 
    

    样例输出 Copy

    2 
    2 
    2 
    8 15 
    8 15 
    15 8 
    21 10 5 39 
    5 10 21 39 
    5 10 39 21 
    #include<iostream>
    #include<algorithm>
    #include<cmath>
    #include<vector>
    #include<cstring>
    #include<string.h>
    #include<queue>
    #include<map>
    #include<cmath>
    #define OK 1
    #define ERROR 0
    #define MAX 100020
    const double eps=1e-5;
    const int maxn=1010;
    #define MAXSIZE 110
    typedef long long LL;
    using namespace std;
    
    
    typedef struct node{
        int high;
        int data;
        struct node *lchild,*rchild;
    }BiTNode,*BiTree;
    
    //先序
    void preOrder(BiTree T){
        if(T==NULL){
            return ;
        }
        printf("%d ",T->data);
        preOrder(T->lchild);
        preOrder(T->rchild);
    }
    //中序
    void InOrder(BiTree T){
        if(T==NULL){
            return ;
        }
        InOrder(T->lchild);
        printf("%d ",T->data);
        InOrder(T->rchild);
    }
    //后序
    void postOrder(BiTree T){
        if(T==NULL){
            return ;
        }
        postOrder(T->lchild);
        postOrder(T->rchild);
        printf("%d ",T->data);
    }
    //插入新结点
    void Insert(BiTree &T,int x){
        if(T==NULL){
            T=new BiTNode;
            T->data=x;
            T->lchild=NULL;
            T->rchild=NULL;
        }else{
            if(x<T->data){
                Insert(T->lchild,x);
            }
            else if(x>T->data){
                Insert(T->rchild,x);
            }
        }
    }
    
    string st;
    int main(){
        int n;
        int m[maxn];
        while(scanf("%d",&n)!=EOF){
            BiTree T=NULL;
            for(int i=0;i<n;i++){
            scanf("%d",&m[i]);
            }
            for(int i=0;i<n;i++){
                Insert(T,m[i]);
            }
            preOrder(T);
            printf("
    ");
            InOrder(T);
            printf("
    ");
            postOrder(T);
            printf("
    ");
        }
        return 0;
    }
  • 相关阅读:
    置顶功能改进
    Skin设计小组新作品发布—绿草蓝天
    代码着色功能改进
    增加了将文章收藏至网摘的功能
    [公告]C++博客开通
    [新功能]显示文章所属分类
    新Skin发布
    北京.NET俱乐部活动公告
    正式开始学习.NET 2.0
    关于共同学习.NET 2.0的想法
  • 原文地址:https://www.cnblogs.com/dreamzj/p/13687381.html
Copyright © 2011-2022 走看看