POJ 2828 Buy Tickets

来源:互联网 发布:淘宝如何设置公益宝贝 编辑:程序博客网 时间:2024/05/24 05:03

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

#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;}

	
				
		
原创粉丝点击