/*
* Tree Sort
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define SIZE (100)
struct _tree {
struct _tree *less;
struct _tree *more;
int value;
};
typedef struct _tree TREE;
TREE *addTreeValue(TREE *tree, int value);
TREE *addTreeValues(TREE *tree, int *array, int offset, int size);
TREE *newTree(int value);
void releaseTree(TREE *tree);
int getTreeSize(TREE *tree);
int getTreeValues(TREE *tree, int *array, int offset, int size);
int main(void) {
int list[SIZE];
int i;
int c;
TREE *tree;
for (i = 0; i < 20; i++)
tree = addTreeValues(NULL, list, 0, 20);
c = getTreeSize(tree);
if (c > SIZE) {
c = SIZE;
}
getTreeValues(tree, list, 0, c);
for (i = 0; i < c; i++) {
printf("%d: %d\n", i
, list
[i
]); }
releaseTree(tree);
return 0;
}
TREE *addTreeValue(TREE *tree, int value) {
if (tree == NULL) {
return newTree(value);
}
if (tree->value < value) {
tree->more = addTreeValue(tree->more, value);
} else {
tree->less = addTreeValue(tree->less, value);
}
return tree;
}
TREE *addTreeValues(TREE *tree, int *array, int offset, int size) {
int i;
array += offset;
for (i = 0 ; i < size; i++) {
tree = addTreeValue(tree, *array);
array++;
}
return tree;
}
TREE *newTree(int value) {
TREE *tree;
tree
= (TREE
*)calloc(1, sizeof(TREE
)); tree->less = NULL;
tree->more = NULL;
tree->value = value;
return tree;
}
void releaseTree(TREE *tree) {
if (tree == NULL) {
return;
}
releaseTree(tree->less);
releaseTree(tree->more);
}
int getTreeSize(TREE *tree) {
int count = 1;
if (tree == NULL) {
return 0;
}
count += getTreeSize(tree->less);
count += getTreeSize(tree->more);
return count;
}
int getTreeValues(TREE *tree, int *array, int offset, int size) {
int count = 0;
if ((tree == NULL) || (array == NULL)) {
return 0;
}
count += getTreeValues(tree->less, array, offset, size);
if (count >= size) {
return count;
}
*(array + offset + count) = tree->value;
count++;
if (count >= size) {
return count;
}
count += getTreeValues(tree->more, array, offset + count, size - count);
return count;
}
LyoKICogVHJlZSBTb3J0CiAqCiAqLwojaW5jbHVkZSA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