zcmu——4399二叉排序树(构建二叉树)

题目链接:

#include<cstdio>
#include<iostream>
#include<map>
#include<algorithm>
#include<vector>
#include<cmath>
#include<cstring>
using namespace std;
struct node{
    int data;
    node* lchild;
    node* rchild;
};
int a[1001];
void preorder(node* root)
{
   if(root==NULL)
        return;
   printf("%d ",root->data);
   preorder(root->lchild);
   preorder(root->rchild);
}
void inorder(node* root)
{
    if(root==NULL)
        return;
    inorder(root->lchild);
    printf("%d ",root->data);
    inorder(root->rchild);
}
void postorder(node* root)
{
    if(root==NULL)
        return;
    postorder(root->lchild);
    postorder(root->rchild);
    printf("%d ",root->data);
}
node* newNode(int v)
{
    node* Node=new node;
    Node->data=v;
    Node->lchild=Node->rchild=NULL;
    return Node;
}
void insert(node* &root,int x)
{
    if(root==NULL)
    {
        root=newNode(x);
        return;
    }
    if(x==root->data)
        return;
    else if(x<root->data)
        insert(root->lchild,x);
    else if(x>root->data)
   insert(root->rchild,x);
}
node* create(int data[],int n)
{
    node* root=NULL;
    for(int i=0;i<n;i++)
    {
        insert(root,data[i]);
    }
    return root;
}
int main()
{
    int t;
    while(~scanf("%d",&t))
    {
    for(int i=0;i<t;i++)
    {
        scanf("%d",&a[i]);
    }
    node* root=create(a,t);
    preorder(root);
    printf("\n");
    inorder(root);
    printf("\n");
    postorder(root);
    printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42232118/article/details/82558388