码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 3999 The order of a Tree 二叉树

时间:2015-05-14 16:31:18      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

#include <iostream>
#include <cstdlib>
#include <string.h>
#include <algorithm>
#define ss(a)  scanf("%d",&a)
#define ss64(a)  scanf("%I64d",&a)
using namespace std;

typedef struct Node
{
    struct Node *l;
	struct Node *r;
	int num;
}*node;

void creat(node &T,int num)             //此处的&的引用是关键
{
   if (T == NULL)
   {
       T = (node)malloc(sizeof(Node));
	   T->num = num;
	   T->l = NULL;
	   T->r = NULL;;
   }
   else
	   if (num < T->num)
	   {
		   creat(T->l,num);
	   }
	   else
	   {
		   creat(T->r,num);
	   }
   
}


void post_visit(node T,int x)
{
    if (T != NULL)
    {
		if(x)
		   cout<<T->num;
		else
		   cout<<" "<<T->num;
		post_visit(T->l,0);
		post_visit(T->r,0);
    }
}

int main()
{
	int i,n,m,sum,cnt,j;
	int num;
	node T=NULL;
	while(~ss(n))
	{
		for (i=0;i<n;i++)
        {
			 ss(num);
			 creat(T,num);
		}
        post_visit(T,1);  
		cout<<endl;
	}
    return 0;
}


考察二叉树的创建以及先序遍历

The order of a Tree

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1337    Accepted Submission(s): 675


Problem Description
As we know,the shape of a binary search tree is greatly related to the order of keys we insert. To be precisely:
1.  insert a key k to a empty tree, then the tree become a tree with
only one node;
2.  insert a key k to a nonempty tree, if k is less than the root ,insert
it to the left sub-tree;else insert k to the right sub-tree.
We call the order of keys we insert “the order of a tree”,your task is,given a oder of a tree, find the order of a tree with the least lexicographic order that generate the same tree.Two trees are the same if and only if they have the same shape.
 

Input
There are multiple test cases in an input file. The first line of each testcase is an integer n(n <= 100,000),represent the number of nodes.The second line has n intergers,k1 to kn,represent the order of a tree.To make if more simple, k1 to kn is a sequence of 1 to n.
 

Output
One line with n intergers, which are the order of a tree that generate the same tree with the least lexicographic.
 

Sample Input
4 1 3 4 2
 

Sample Output
1 3 2 4
 

Source

HDU 3999 The order of a Tree 二叉树

标签:

原文地址:http://blog.csdn.net/xinwen1995/article/details/45722299

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!