二叉排序树(王道)

 

#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;
}

 

posted @ 2018-03-12 12:33  Shaw_喆宇  阅读(192)  评论(0编辑  收藏  举报