二叉排序树的建立以及遍历

题目描述

输入一系列整数,建立二叉排序数,并进行前序,中序,后序遍历。

输入描述:

 
  

输入第一行包括一个整数n(1<=n<=100)。 接下来的一行包括n个整数。

输出描述:

 
  

可能有多组测试数据,对于每组数据,将题目所给数据建立一个二叉排序树,并对二叉排序树进行前序、中序和后序遍历。 每种遍历结果输出一行。每行最后一个数据之后有一个空格。 输入中可能有重复元素,但是输出的二叉树遍历序列中重复元素不用输出。

示例1

输入

 
   

5 1 6 5 9 8

输出

 
   

1 6 5 9 8 1 5 6 8 9 5 8 9 6 1


#include<iostream>
using namespace std;
struct node
{
    int x;
    node * lchild;
    node * rchild;
}Tree[200];
int size=0;
node * create()  //建树都会有的函数
{
    Tree[size].lchild=Tree[size].rchild=NULL;
    return &Tree[size++];
}
node* build(node* tree,int x)
{
    if(tree==NULL)//说明是第一个结点,此时的x就是根结点的值
    {
        tree=create();
        tree->x=x;
        return tree;
    }
    else if(x>tree->x)
    {
        tree->rchild=build(tree->rchild,x);//容易写错,这里是建立tree的左子树
    }
    else if(x<tree->x)
    {
        tree->lchild=build(tree->lchild,x); //建立tree的右子树
    }
    return tree;
}
void before(node * tree)
{
    cout<<tree->x<<' ';
    if(tree->lchild!=NULL)before(tree->lchild);    //不等于NULL条件不能随便少
    if(tree->rchild!=NULL)before(tree->rchild);
}
void mid(node * tree)
{
    if(tree->lchild!=NULL)mid(tree->lchild);
    cout<<tree->x<<' ';
    if(tree->rchild!=NULL)mid(tree->rchild);
}
void post(node * tree)
{
    if(tree->lchild!=NULL)post(tree->lchild);
    if(tree->rchild!=NULL)post(tree->rchild);
    cout<<tree->x<<' ';
}
int main()
{
    int n;
    while(cin>>n)
    {
        node *tree=NULL;
        int num;
        for(int i=0;i<n;i++)
        {
            cin>>num;
            tree=build(tree,num);
        }
        mid(tree);
        cout<<endl;
        before(tree);
        cout<<endl;
        post(tree);
        cout<<endl;

    }
}

猜你喜欢

转载自blog.csdn.net/qq_38030194/article/details/80300928