POJ 2828 Buy Tickets

树的中序遍历,具体思路见代码。。。

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <queue>

using namespace std;

struct N
{
    int ans,data;//ans存贮的为该节点的左子树有 ans-1 个节点
    N *l,*r;     //即该节点为 以该节点为根节点的树中的位置
};

N *creat()
{
    N *root = (N *)malloc(sizeof(N));
    root->l = root->r = NULL;
    return root;
}

void insert(int site,int data,N *&root)
{
    if(root == NULL)
    {
        root = creat();
        root->ans = 1;
        root->data = data;
        return ;
    }

    if(site < root->ans)
    {
        root->ans++;
        insert(site,data,root->l);//若site < ans则说明要寻找的点在左子树中
    }
    else
    {
        insert(site-root->ans,data,root->r);
        //因为此节点的右子树中有 ans-1 个节点
        //所以只需在右子树中寻找 第 site-ans 个节点
    }
}

bool MarkBlance;

void output(N *root)//树的中序遍历
{
    if(root == NULL)
    {
        return ;
    }
    output(root->l);
    if(MarkBlance == true)
    {
        printf("%d",root->data);
        MarkBlance = false;
    }
    else
    {
        printf(" %d",root->data);
    }
    output(root->r);
}

int main()
{
    int n;
    int site,data;

    N *root ;

    while(scanf("%d",&n) != EOF)
    {
        root = NULL;
        while(n--)
        {
            scanf("%d %d",&site,&data);
            insert(site,data,root);
        }
        MarkBlance = true;//控制空格
        output(root);
        cout<<endl;
    }
    return 0;
}


你可能感兴趣的:(POJ 2828 Buy Tickets)