HDU 3999----The order of a Tree(二叉树的前序遍历)

来源:互联网 发布:电池校准软件 编辑:程序博客网 时间:2024/05/17 06:49

二叉树的建立,在主函数里都是返回的是根节点


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
41 3 4 2
 

Sample Output
1 3 2 4
#include<cstdio>struct tree{int data;tree *left,*right;}*root;bool flag;int k,ans[100010];tree *build(tree *root,int v)   //建立二叉树 {if(root==NULL){root=new tree;root->data=v;root->left=root->right=NULL;return root;}if(root->data>v) root->left=build(root->left,v);else root->right=build(root->right,v);return root;}void preorder(tree *root)  {      if(root==NULL)  return ;      ans[k++]=root->data;     preorder(root->left);  //递归调用,先序遍历左子树     preorder(root->right); //递归调用,先序遍历右子树 }  int main(){int n,v,i;while(~scanf("%d",&n)){root=NULL;k=0;while(n--){scanf("%d",&v);root=build(root,v);}preorder(root);for(i=0;i<k-1;i++) printf("%d ",ans[i]);          printf("%d\n",ans[k-1]);  }return 0;}




0 0
原创粉丝点击