1. 程式人生 > 實用技巧 >HDU 3999 The order of a Tree (排序二叉樹的先序遍歷)

HDU 3999 The order of a Tree (排序二叉樹的先序遍歷)

題目

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

思路

給你一個序列,讓你根據這個序列建立排序二叉樹,然後問你一個序列,這個序列最後建立的排序二叉樹和我給出的是一顆,且字典序最小。那麼由排序二叉樹的性質我可以知道,先序遍歷的序列一定是字典序最小的。

Code

#include<vector>
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
void check_max (int &a,int b) {a=max (a,b);}
void check_min (int &a,int b) {a=min (a,b);}
vector <int> v;
int n;
struct node {
	int data;
	node *leftchild,*rightchild;
    node () {
		leftchild=NULL;
		rightchild=NULL;
	}
};

void insert (node *&root,int data) {
	if (root==NULL) {
		root=new node ();
		root->data=data;
		return ;
	}
	else if (root->data==data) return ;
	else if (data>root->data) insert (root->rightchild,data);
	else if (root->rightchild,data) insert (root->leftchild,data);
	return ;
}

node * build () {
	node *root=NULL;
	for (auto it:v) {
		insert (root,it);
	}
	return root;	
}

void pre_travel (node *root,int flag) {
	if (root==NULL) return ;
	if (flag==1) printf ("%d",root->data);
	else printf (" %d",root->data);
	pre_travel (root->leftchild,++flag);
	pre_travel (root->rightchild,++flag);
	return ;
}

int main () {
    while (scanf ("%d",&n)!=EOF) {
		v.clear ();
		for (int i=1;i<=n;i++) {
			int x; scanf ("%d",&x);
			v.push_back (x);
		}
		node *root=build ();
		pre_travel (root,1);
		printf ("\n");
	}
	return 0;
}