1. 程式人生 > >九度OJ題目1201:二叉排序樹

九度OJ題目1201:二叉排序樹

紀念一下終於在二叉樹上的程式碼準確率,但還是在給root分配空間的時候忘記要寫了  悲劇

還沒看到提示要考慮忽略重複元素,這個好解決

題目描述:

    輸入一系列整數,建立二叉排序數,並進行前序,中序,後序遍歷。

輸入:

    輸入第一行包括一個整數n(1<=n<=100)。
    接下來的一行包括n個整數。

輸出:

    可能有多組測試資料,對於每組資料,將題目所給資料建立一個二叉排序樹,並對二叉排序樹進行前序、中序和後序遍歷。
    每種遍歷結果輸出一行。每行最後一個數據之後有一個空格。

樣例輸入:
5
1 6 5 9 8
樣例輸出:
1 6 5 9 8 
1 5 6 8 9 
5 8 9 6 1 
提示:

輸入中可能有重複元素,但是輸出的二叉樹遍歷序列中重複元素不用輸出。

#include<stdio.h>
#include<iostream>
using namespace std;
int n;
int a[1004];
struct Tree
{
    int v;
    Tree * lf;
    Tree * rt;
};
Tree *root;
void buildtree(Tree *r,int a)
{
    if(a<(r->v))
    {
        if((r->lf) == NULL)
        {
            Tree* nr = new Tree();
            nr->v = a;
            r->lf = nr;
        }
        else
            buildtree(r->lf,a);
    }
    else if(a>r->v)
    {
        if(r->rt == NULL)
        {
            Tree* nr = new Tree();
            nr->v = a;
            nr->lf = NULL;
            nr->rt = NULL;
            r->rt = nr;
        }
        else
            buildtree(r->rt,a);
    }
}
void firstravel(Tree *r)
{
    printf("%d ",r->v);
    if(r->lf!=NULL)
        firstravel(r->lf);
    if(r->rt!=NULL)
        firstravel(r->rt);
}
void midtravel(Tree *r)
{
    if(r->lf!=NULL)
        midtravel(r->lf);
    printf("%d ",r->v);
    if(r->rt!=NULL)
        midtravel(r->rt);
}
void lastravel(Tree *r)
{
    if(r->lf!=NULL)
        lastravel(r->lf);
    if(r->rt!=NULL)
        lastravel(r->rt);
    printf("%d ",r->v);
}
int main()
{
    while(~scanf("%d",&n)&&n)
    {
        root = new Tree();//****切記給根節點分配空間
        for(int i  = 0 ; i < n ;i++)
            scanf("%d",&a[i]);
        root->v = a[0];
        for(int i  = 1 ; i < n ;i++)
        {
            buildtree(root,a[i]);
        }
        firstravel(root);
        printf("\n");
        midtravel(root);
        printf("\n");
        lastravel(root);
        printf("\n");
    }
    return 0;
}