zoukankan      html  css  js  c++  java
  • 二叉排序树(王道)

    #include <iostream>
    #include<cstdio>
    using namespace std;
    
    struct Nod
    e{
        Node* lchild;
        Node* rchild;
        int num;
    };
    
    struct Node Tree[50];
    int loc;
    Node *create(){//创建
        Tree[loc].lchild = Tree[loc].rchild = NULL;
        return &Tree[loc++];
    }
    
    void preOrder(Node* T){//前序遍历
        printf("%d",T->num);
        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->num);
        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->num);
    }
    
    Node *insertNode(Node *T,int x){//插入数字
        if(T == NULL){
            T = create();
            T->num = x;
        }
        else if(x < T->num)
            T->lchild = insertNode(T->lchild,x);
        else if(x > T->num)
            T->rchild = insertNode(T->rchild,x);
        return T;
    }
    
    int main()
    {
        int n;
        cin >> n;
        while(n--){
            int n2;
            cin >> n2;
            Node *T = NULL;
            loc = 0;
            for(int i=0;i<n2;i++){
                int x = 0;
                cin >> x;
                T = insertNode(T,x);
            }
            preOrder(T);
            cout << endl;
            inOrder(T);
            cout << endl;
            postOrder(T);
            cout << endl;
        }
        return 0;
    }
  • 相关阅读:
    继续学习:C语言关键字
    继续学习C:运算符
    C语言小程序(八)、统计字母个数
    C语言小程序(七)、石头剪刀布
    飞思卡尔总结
    [原]NYOJ-子串和44
    C++函数重载详解
    趣味Shell
    C语言小程序(六)、数组操作
    C语言小程序(五)、数组查询
  • 原文地址:https://www.cnblogs.com/xym4869/p/8548567.html
Copyright © 2011-2022 走看看