csu 1005 BST(二叉排序树水题)

来源:互联网 发布:体检数据 编辑:程序博客网 时间:2024/06/04 00:21
#include <iostream>#include <map>#include <stdlib.h>#include <cstdio>#include <string>using namespace std;bool flag;typedef struct BSTNode{    int data;    struct BSTNode *left,*right;}BSTNode,*BSTree;BSTree CreatBST(BSTree T,int temp){   if(!T)   {    T=(BSTree)malloc(sizeof(BSTNode));    T->data=temp;    T->left=T->right=NULL;   }   else if(temp<T->data)    T->left=CreatBST(T->left,temp);   else     T->right=CreatBST(T->right,temp);return T;}void Preorder(BSTree T){    if(T)    {        if(!flag)        {            cout<<T->data;            flag=true;        }        else         {            cout<<" "<<T->data;        }        Preorder(T->left);        Preorder(T->right);    }}void Inorder(BSTree T){    if(T)    {        Inorder(T->left);         if(!flag)        {            cout<<T->data;            flag=true;        }        else         {            cout<<" "<<T->data;        }        Inorder(T->right);    }}void Houorder(BSTree T){    if(T)    {        Houorder(T->left);        Houorder(T->right);         if(!flag)        {            cout<<T->data;            flag=true;        }        else         {            cout<<" "<<T->data;        }    }}int main(){    int T,n,x;    cin>>T;    while(T--)    {        BSTree root=NULL;        cin>>n;        for(int i=0;i<n;i++)        {            cin>>x;           root = CreatBST(root,x);        }        flag=false;        Preorder(root);        cout<<endl;        flag=false;        Inorder(root);        cout<<endl;        flag=false;        Houorder(root);        cout<<endl<<endl;    }    return 0;}