您的位置:首页 > 其它

[HDOJ1106]排序

2015-10-22 21:39 375 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1106

二叉树排序输出,测试此数据结构用......



#include <cstdio>
#include <iostream>

using namespace std;

#ifndef _KIRAI_BST
#define _KIRAI_BST

namespace kirai {
template<class type>
struct bstnode {
typedef bstnode<type>* np;
type _data;
np left;
np right;
bstnode<type>() { left = NULL; right = NULL; }
bstnode<type>(const int& x) : _data(x) { bstnode<type>(); }
};

template<class type>
class bst {
typedef bstnode<type>* np;
typedef bstnode<type> nt;

public:
bst() { _root = NULL; }
// ~bst();
bool empty() const { return _root == NULL; }
void insert(const type&);
bool remove(const type&);
bool query(const type&) const;
bool change(const type&);

public:
void preorder(void(*visit)(type)) { _preorder(_root, visit); };
void inorder(void(*visit)(type)) { _inorder(_root, visit); };
void postorder(void(*visit)(type)) { _postorder(_root, visit); };

protected:
void _insert(np, const type&);
void _inorder(np, void(*)(type));
void _postorder(np, void(*)(type));
void _preorder(np, void(*)(type));
private:
np _root;
};

template <class type>
void bst<type>::insert(const type& x) {
if (empty()) {
np tmp = new nt;
_root = tmp;
_root->_data = x;
return;
}
_insert(_root, x);
return;
}

// x () than _data, then put x into (). : larger:right, smaller:left
template <class type>
void bst<type>::_insert(np cur, const type& x) {
if (x >= cur->_data) {
if (cur->right == NULL) {
np tmp = new nt;
cur->right = tmp;
tmp->_data = x;
return;
}
else {
_insert(cur->right, x);
}
}
else {
if (cur->left == NULL) {
np tmp = new nt;
cur->left = tmp;
tmp->_data = x;
return;
}
else {
_insert(cur->left, x);
}
}
}
template <class type>
void bst<type>::_preorder(np cur, void(*visit)(type data)) {
if (cur != NULL) {
(*visit)(cur->_data);
_preorder(cur->left, visit);
_preorder(cur->right, visit);
}
}

template <class type>
void bst<type>::_inorder(np cur, void(*visit)(type data)) {
if (cur != NULL) {
_inorder(cur->left, visit);
(*visit)(cur->_data);
_inorder(cur->right, visit);
}
}

template <class type>
void bst<type>::_postorder(np cur, void(*visit)(type data)) {
if (cur != NULL) {
_postorder(cur->left, visit);
_postorder(cur->right, visit);
(*visit)(cur->_data);
}
}
}

#endif

char bf[1001];
char *pt, *five = "5";
int num[1000];
int n, cnt;

void convert(int x) {
num[cnt++] = x;
}

int main() {
while(~scanf("%s", bf)) {
// freopen("in", "r", stdin);
char* tmp;
kirai::bst<int> accepted;
pt = bf;
n = 0;
pt = strtok(bf, five);
while(pt != NULL) {
tmp = pt;
pt = strtok(NULL, five);
num
= atoi(tmp);
n++;
}
for(int i = 0; i < n; i++) {
accepted.insert(num[i]);
}
cnt = 0;
accepted.inorder(convert);
printf("%d", num[0]);
for(int i = 1; i < cnt; i++) {
printf(" %d", num[i]);
}
printf("\n");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: