#ifndef _BIN_TREE_H #define _BIN_TREE_H #include <stdio.h> #include <stdlib.h> #include <stddef.h> struct _Tree_node { int data; struct _Tree_node *left; struct _Tree_node *right; }; typedef int element_type; typedef struct _Tree_node *search_tree; typedef struct _Tree_node *position; position find(element_type __x, search_tree tree) { if (tree == NULL) { printf("No this node!\n"); return NULL; } else if (__x < tree->data) { return find(__x, tree->left); } else if (__x > tree->data) { return find(__x, tree->right); } else { return tree; } } position find_min(search_tree tree) { if (tree == NULL) { return NULL; } else if (tree->left == NULL) { return tree; } else { return find_min(tree->left); } } position find_max(search_tree tree) { if (tree == NULL) { return NULL; } else if (tree->right == NULL) { return tree; } else { return find_max(tree); } } void insert(element_type __x, search_tree *tree) { if (*tree == NULL) { *tree = (search_tree) malloc((size_t) 1 * sizeof(struct _Tree_node)); if (*tree == NULL) { printf("out of memory.\n"); exit(1); } else { (*tree)->data = __x; (*tree)->left = (*tree)->right = NULL; } } else if (__x < (*tree)->data) { insert(__x, &((*tree)->left)); } else if (__x > (*tree)->data) { insert(__x, &((*tree)->right)); } else { ; } } void delete(element_type __x, search_tree *tree) { position tmp = NULL; if (*tree == NULL) { printf("Not found!\n"); } else if (__x < (*tree)->data) { delete(__x, &((*tree)->left)); } else if (__x > (*tree)->data) { delete(__x, &((*tree)->right)); } else if ((*tree)->left && (*tree)->right) { tmp = find_min((*tree)->right); (*tree)->data = tmp->data; delete((*tree)->data, &((*tree)->right)); } else { tmp = *tree; if ((*tree)->left == NULL) { *tree = (*tree)->right; } else if ((*tree)->right == NULL) { *tree = (*tree)->left; } free(tmp); } } void print_by_pre(search_tree tree) { if (tree != NULL) { printf("value is %d.\n", tree->data); print_by_pre(tree->left); print_by_pre(tree->right); } } void print_by_in(search_tree tree) { if (tree != NULL) { print_by_in(tree->left); printf("value is %d.\n", tree->data); print_by_in(tree->right); } } void print_by_post(search_tree tree) { if (tree != NULL) { print_by_post(tree->left); print_by_post(tree->right); printf("value is %d.\n", tree->data); } } #endif
原文地址:http://blog.csdn.net/tobebetterprogrammer/article/details/45031323