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

    题目描述:

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

    输入:

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

    输出:

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

    样例输入:
    5
    1 6 5 9 8
    样例输出:
    1 6 5 9 8 
    1 5 6 8 9 
    5 8 9 6 1 
    提示:

    输入中可能有重复元素,但是输出的二叉树遍历序列中重复元素不用输出。

    #include<stdio.h>
    #include<string.h>
    struct Node{ //树结点结构体
        Node *lchild;
        Node *rchild;
        int c;
    }Tree[100];
    
    int loc;//静态数组中已经分配的结点个数
    Node *creat(){//申请一个结点空间,返回指向其的指针
        Tree[loc].lchild = Tree[loc].rchild = NULL;
        return &Tree[loc++];
    }
    
    void preOrder(Node * T){//前序遍历树
        printf("%d ",T->c );
        if(T->lchild != NULL)
            preOrder(T->lchild );
        if(T->rchild != NULL)
            preOrder(T->rchild );
        
    }
    
    void inOrder(Node * T){//中序遍历树
    
        if(T->lchild != NULL)
            inOrder(T->lchild );    
        printf("%d ",T->c );
        if(T->rchild != NULL)
            inOrder(T->rchild );
        
    }
    
    void postOrder(Node * T){//后序遍历树
        if(T->lchild != NULL)
            postOrder(T->lchild );
        if(T->rchild != NULL)
            postOrder(T->rchild );
        printf("%d ",T->c );
    }
    
    Node * insert(Node* T,int x){//插入数字
        if(T==NULL){
            T = creat();
            T->c = x;
            return T;
        }
        else if(T->c>x){
            T->lchild = insert(T->lchild,x);}
        else if(T->c<x){
            T->rchild = insert(T->rchild,x);}
        return T;
    }
    
    int main()
    {
        int n;
        while(scanf("%d",&n)!=EOF){
            loc = 0;
            Node * T = NULL;
            for(int i=0;i<n;i++){
                int x;
                scanf("%d",&x);
                T = insert(T,x);
            }
            preOrder(T);
            printf("
    ");
            inOrder(T);
            printf("
    ");
            postOrder(T);
            printf("
    ");
        }
        return 0;
    }
  • 相关阅读:
    The Quad
    将OrCAD Capture CIS的设计文件(.dsn)导入到PADS Logic VX.2.3
    OrCAD Capture CIS 16.6 将版本16.6的设计文件另存为版本16.2的设计文件
    Eclipse IDE 添加jar包到Java工程中
    PADS Logic VX.2.3 修改软件界面语言
    切换Allegro PCB Editor
    Allegro PCB Design GXL (legacy) 将brd文件另存为低版本文件
    Allegro PCB Design GXL (legacy) 设置自动保存brd文件
    Could not create an acl object: Role '16'
    windows 下apache开启FastCGI
  • 原文地址:https://www.cnblogs.com/rickhsg/p/3650728.html
Copyright © 2011-2022 走看看