排序演算法七:排序二叉樹
阿新 • • 發佈:2018-12-11
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <time.h> #define TREE_TYPE int typedef struct TREE_NODE { TREE_TYPE value; struct TREE_NODE *left; struct TREE_NODE *right; }TreeNode; static TreeNode *tree = NULL; void insert(TREE_TYPE value) { TreeNode *current; TreeNode **link; link = &tree; while((current = *link) != NULL) { if (value < current->value) link = ¤t->left; else { link = ¤t->right; } } current = malloc(sizeof(TreeNode)); assert(current != NULL); current->value = value; current->left = NULL; current->right = NULL; current->right = NULL; *link = current; } TreeNode *find(TreeNode *current, TREE_TYPE value) { while(current != NULL && current->value != value) { if (value < current->value) current = current->left; else current = current->right; } if (current != NULL) return current; else return NULL; } void delete(TREE_TYPE value) { TreeNode *current; TreeNode **link; link = &tree; while((current = *link) != NULL && value != current->value) { if (value < current->value) link = ¤t->left; else link = ¤t->right; } assert(current != NULL); if (current->left == NULL && current->right == NULL) { *link = NULL; free(current); } else if (current->left == NULL || current->right == NULL) { if (current->left != NULL) *link = current->left; else *link = current->right; free(current); } else {//左右子樹都不為空 TreeNode *this_child; TreeNode *next_child; /*轉左,然後向右到盡頭*/ this_child = current; next_child = this_child->left; while (next_child->right != NULL) { this_child = next_child; next_child = next_child->right; } current->value = next_child->value; if (this_child != current) this_child->right = next_child->left; else this_child->left = next_child->left; free(next_child); } } static void pre_order_traverse(TreeNode *current, void (*callback)(TREE_TYPE value)) { if (current != NULL) { callback(current->value); pre_order_traverse(current->left, callback); pre_order_traverse(current->right, callback); } } void print_tree(TREE_TYPE value) { printf("%3d", value); } void inner_order_traverse(TreeNode *current, void (*callback)(TREE_TYPE value)) { if (current != NULL) { inner_order_traverse(current->left, callback); callback(current->value); inner_order_traverse(current->right, callback); } } void post_order_traverse(TreeNode *current, void (*callback)(TREE_TYPE value)) { if (current != NULL) { post_order_traverse(current->left, callback); post_order_traverse(current->right, callback); callback(current->value); } } int main(int argc, char *argv[]) { TreeNode *p; srand(time(NULL)); int i = 0, value = 0; for (i = 0; i < 5; i++) { value = rand() % 100; insert(i); } // pre_order_traverse(tree, print_tree); //前序 inner_order_traverse(tree, print_tree); //中序 printf("\n"); // post_order_traverse(tree, print_tree); //後序 delete(1); //刪除某個節點 inner_order_traverse(tree, print_tree); return 0; }