C语言-二叉树
使用tree定义一个node指针地址,作为树块,node里面定义当前的val,左子树和右子树
02tree.h的定义
/* 二叉树 */ #include "02tree.h" void tree_init(tree *p_tree) { p_tree->p_node = NULL; //把方块里的指针形成一个空树(没有圆圈的树) } void tree_deinit(tree* p_tree) { if (!p_tree->p_node) { return ; } tree_deinit(&(p_tree->p_node->left)); tree_deinit(&(p_tree->p_node->right)); free(p_tree->p_node); p_tree->p_node = NULL; } tree* tree_search(tree* p_tree, int val) { if (!p_tree->p_node) { return (tree* )p_tree; } if (p_tree->p_node->val == val) { return (tree* )p_tree; } else if (p_tree->p_node->val > val) { return tree_search(&p_tree->p_node->left, val); } else { return tree_search(&p_tree->p_node->right, val); } } int tree_insert(tree* p_tree, int val) { node* p_node = NULL; tree* p_pos = tree_search(p_tree, val); if (p_pos->p_node) { return 0; } p_node = (node* )malloc(sizeof(node)); if(!p_node) { free(p_node); p_node = NULL; return 0; } p_node->val = val; p_node->left.p_node = NULL; p_node->right.p_node = NULL; p_pos->p_node = p_node; } void tree_miter(const tree* p_tree, pfunc_t p_func) { if (!p_tree->p_node) { return ; //没有数的情况下 } tree_miter(&p_tree->p_node->left, p_func); p_func(p_tree->p_node->val); tree_miter(&p_tree->p_node->right, p_func); }
02tree.c
/* 二叉树 */ #include "02tree.h" void tree_init(tree *p_tree) { p_tree->p_node = NULL; //把方块里的指针形成一个空树(没有圆圈的树) } void tree_deinit(tree* p_tree) { if (!p_tree->p_node) { return ; } tree_deinit(&(p_tree->p_node->left)); tree_deinit(&(p_tree->p_node->right)); free(p_tree->p_node); p_tree->p_node = NULL; } tree* tree_search(tree* p_tree, int val) { if (!p_tree->p_node) { return (tree* )p_tree; } if (p_tree->p_node->val == val) { return (tree* )p_tree; } else if (p_tree->p_node->val > val) { return tree_search(&p_tree->p_node->left, val); } else { return tree_search(&p_tree->p_node->right, val); } } int tree_insert(tree* p_tree, int val) { node* p_node = NULL; tree* p_pos = tree_search(p_tree, val); if (p_pos->p_node) { return 0; } p_node = (node* )malloc(sizeof(node)); if(!p_node) { free(p_node); p_node = NULL; return 0; } p_node->val = val; p_node->left.p_node = NULL; p_node->right.p_node = NULL; p_pos->p_node = p_node; } void tree_miter(const tree* p_tree, pfunc_t p_func) { if (!p_tree->p_node) { return ; //没有数的情况下 } tree_miter(&p_tree->p_node->left, p_func); p_func(p_tree->p_node->val); tree_miter(&p_tree->p_node->right, p_func); }
02main.c
/* 二叉树主函数 */ #include "02tree.h" void print(int val) { printf("%d ", val); } int main() { tree t = {0}; tree_init(&t); tree_insert(&t, 10); tree_insert(&t, 20); tree_miter(&t, print); printf("\n"); tree_deinit(&t); }
每天更新pyQt5内容