#include <stdio.h>
#include <stdlib.h>
typedef struct Node* Node;
struct Node {
int value;
Node left;
Node right;
};
typedef struct Tree* Tree;
struct Tree {
Node root;
};
void Tree_add(Tree tree, int value) {
Node n;
Node p;
n
= calloc(1,sizeof(struct Node
)); n->value = value;
n->left = NULL;
n->right = NULL;
if (tree->root == NULL) {
tree->root = n;
} else {
p = tree->root;
while (1) {
if (value < p->value) {
if (p->left == NULL) {
p->left = n;
break;
} else {
p = p->left;
}
} else {
if (p->right == NULL) {
p->right = n;
break;
} else {
p = p->right;
}
}
}
}
}
void print_node(Node n,size_t depth){
while(depth--){
}
}
void dump_tree_impl(Node n,size_t depth){
if(n){
dump_tree_impl(n->right,depth + 1);
print_node(n,depth);
dump_tree_impl(n->left,depth + 1);
}
}
void free_node(Node n){
if(n){
free_node(n->right);
free_node(n->left);
}
}
void free_tree(Tree t){
free_node(t->root);
}
void Tree_dump(Tree tree) {
dump_tree_impl(tree->root,0);
}
int main(void) {
Tree tree
= calloc(1,sizeof(struct Tree
)); Tree_add(tree, 3);
Tree_add(tree, 1);
Tree_add(tree, 5);
Tree_add(tree, 0);
Tree_add(tree, 2);
Tree_add(tree, 4);
Tree_add(tree, 6);
Tree_dump(tree);
free_tree(tree);
return EXIT_SUCCESS;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdGRsaWIuaD4KCnR5cGVkZWYgc3RydWN0IE5vZGUqIE5vZGU7CnN0cnVjdCBOb2RlIHsKICAgaW50IHZhbHVlOwogICBOb2RlIGxlZnQ7CiAgIE5vZGUgcmlnaHQ7Cn07Cgp0eXBlZGVmIHN0cnVjdCBUcmVlKiBUcmVlOwpzdHJ1Y3QgVHJlZSB7CiAgIE5vZGUgcm9vdDsKfTsKCnZvaWQgVHJlZV9hZGQoVHJlZSB0cmVlLCBpbnQgdmFsdWUpIHsKICAgTm9kZSBuOwogICBOb2RlIHA7CiAgIAogICBuID0gY2FsbG9jKDEsc2l6ZW9mKHN0cnVjdCBOb2RlKSk7CiAgIG4tPnZhbHVlID0gdmFsdWU7CiAgIG4tPmxlZnQgPSBOVUxMOwogICBuLT5yaWdodCA9IE5VTEw7CiAgIAogICBpZiAodHJlZS0+cm9vdCA9PSBOVUxMKSB7CiAgICAgIHRyZWUtPnJvb3QgPSBuOwogICB9IGVsc2UgewogICAgICBwID0gdHJlZS0+cm9vdDsKICAgICAgd2hpbGUgKDEpIHsKICAgICAgICAgaWYgKHZhbHVlIDwgcC0+dmFsdWUpIHsKICAgICAgICAgICAgaWYgKHAtPmxlZnQgPT0gTlVMTCkgewogICAgICAgICAgICAgICBwLT5sZWZ0ID0gbjsKICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgICAgIHAgPSBwLT5sZWZ0OwogICAgICAgICAgICB9CiAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgIGlmIChwLT5yaWdodCA9PSBOVUxMKSB7CiAgICAgICAgICAgICAgIHAtPnJpZ2h0ID0gbjsKICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgICAgIHAgPSBwLT5yaWdodDsKICAgICAgICAgICAgfQogICAgICAgICB9CiAgICAgIH0KICAgfQp9Cgp2b2lkIHByaW50X25vZGUoTm9kZSBuLHNpemVfdCBkZXB0aCl7CiAgICB3aGlsZShkZXB0aC0tKXsKICAgICAgICBwdXRjaGFyKCcgJyk7CiAgICB9CiAgICBwcmludGYoIiVkXG4iLG4tPnZhbHVlKTsKfQoKdm9pZCBkdW1wX3RyZWVfaW1wbChOb2RlIG4sc2l6ZV90IGRlcHRoKXsKICAgIGlmKG4pewogICAgICAgIGR1bXBfdHJlZV9pbXBsKG4tPnJpZ2h0LGRlcHRoICsgMSk7CiAgICAgICAgcHJpbnRfbm9kZShuLGRlcHRoKTsKICAgICAgICBkdW1wX3RyZWVfaW1wbChuLT5sZWZ0LGRlcHRoICsgMSk7CiAgICB9Cn0KCn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