HDU3999 The order of a Tree
复习二叉树ing
题目地址
创建一个二叉树,小于根的数放左子树,大于的放右子树,输出和这个数相同的最小字典序,嘛,翻译解释的肯定比我解释的好。
要字典序最小,正好为树的前序遍历,前序遍历并输出就好了。
代码如下:
#include<bits/stdc++.h>
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
typedef long long ll;
const int maxn = 1e5+7;
typedef struct Btree {
int date;
Btree *lchild,*rchild;
} *BT;
void add(BT &T,int m) {
if(T==NULL) {
T=new Btree();
T->date=m;
T->lchild=T->rchild=NULL;
}else if(T->date>m) {
add(T->lchild,m);
}else{
add(T->rchild,m);
}
}
void preorder(BT T,bool m) {
if(T){
if(!m)
cout<<" ";
cout<<T->date;
preorder(T->lchild,0);
preorder(T->rchild,0);
}
}
int main() {
BT T;
int n,m;
while(~scanf("%d",&n)) {
T=NULL;
for(int i=0;i<n;i++) {
cin>>m;
add(T,m);
}
preorder(T,1);
cout<<endl;
}
}