zoukankan      html  css  js  c++  java
  • 二叉树的基本操作之二叉排序树

    //二叉树的基本操作之—建立二叉排序树并遍历
    #include<stdio.h>
    #include<string.h>
    struct Node{
        Node *lchild;
        Node *rchild;
        int c;
    }Tree[110];//静态数组 
    int loc;// 静态数组中被使用的元素个数
    Node *create(){//申请未使用的结点 
        Tree[loc].lchild=Tree[loc].rchild=NULL;
        return &Tree[loc+1];
    } 
    void postOrder(Node *T){//后序遍历
        if(T->lchild!=NULL)
            postOrder(T->lchild);
        if(T->rchild!=NULL)
            postOrder(T->rchild);
        printf("%d ",T->c); 
    }
    void inOrder(Node *T){//中序遍历
        if(T->lchild!=NULL)
            inOrder(T->lchild);
        printf("%d ",T->c); 
        if(T->rchild!=NULL)
            inOrder(T->rchild);    
    }
    void preOrder(Node *T){//前序遍历
        printf("%d ",T->c); 
        if(T->lchild!=NULL)
            preOrder(T->lchild);
        
        if(T->rchild!=NULL)
            preOrder(T->rchild);    
    }
    Node *Insert(Node *T,int x){//将数字x 插入到排序树中 
        if(T==NULL){//当前树为空
            T=create();
            T->c=x;
            return T; 
        }
        else if(x<T->c){//若x小于根结点数值 
            T->lchild=Insert(T->lchild,x);//插到左子树上
        else if(x>T->c)
            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);//插入到排序树中
         
            }
            printf("先序遍历:");
            preOrder(T);
            printf("
    ");
            printf("中序遍历:");
            inOrder(T);
            printf("
    ");
            printf("后序遍历:");
            postOrder(T);
            printf("
    ");
        }
        return 0;
    }
  • 相关阅读:
    小型的Unix系统字符SHELL
    小型的Unix系统字符SHELL
    string 大小写转换
    string 大小写转换
    string 大小写转换
    ACM 的中取模
    ACM 的中取模
    使用adb命令停止APP后台进程的方法
    how to use adb and gdbserver with VirtualBox
    CentOS的KVM实践(虚拟机创建、网桥配置、Spice)
  • 原文地址:https://www.cnblogs.com/Elaine-DWL/p/7106044.html
Copyright © 2011-2022 走看看