链表,队列,栈,二叉树 源码:https://github.com/baitxaps/CPointer
//
//Binary Tree
//
typedef void (*DISPLAY)(void*);
typedef int (*COMPARE)(void*,void*);
typedef struct _employee{
char name[32];
unsigned char age;
}Employee;
/*
指针提供一种维护三个节点之间的关系的直观、动态的方式。可以动态分配节点,将其按需插入树中。
这里使用下面的结构体作为节点,借助void指针可以处理需要的任意类型的数据
*/
typedef struct _tree{
void *data;
struct _tree *left;
struct _tree *right;
}TreeNode;
int compareEmployee(Employee *e1,Employee *e2){
return strcmp(e1->name, e2->name);
}
void displayEmployee(Employee *employee){
printf("%s\t %d\n",employee->name,employee->age);
}
/*
二叉查找树(插入新节点后,这个节点的所有左子节点的值都比父节点小,所有右子节点的值都比父节点的值大)
0.insertNode函数会把一个节点插入二叉查找树,函数第一部分为新节点分配内存并把数据赋给节点,
新节点插入树后总是叶子节点,所以将左子节点和右子节点置为NULL。
1.根节点是以TreeNode指针的指针和形式传递的,因为需要修改传入的函数的指针,而不是指针指向的对象。
如果树非空,进入一个无限循环,直到将新节点插入树中结束
2.每次循环迭代都会比较新节点和当前节点,根据比较结果,将局部root指针置为左子节点或右子节点,这个
root指针总是指向当前节点
3.如果左子节点或右子节点为空,那么就将新节点添加为当前节点的子节点,循环结束
*/
void insertNode(TreeNode **root,COMPARE compare,void *data){
TreeNode *node = (TreeNode *)malloc(sizeof(TreeNode));
node->data = data;
node->left = NULL;
node->right= NULL;
if (*root==NULL) {
*root = node ;
return;
}
while (1) {
if (compare((*root)->data,data)>0) {
if ((*root)->left !=NULL) {
*root = (*root)->left;
}else{
(*root)->left = node;
break;
}
}else{
if ((*root)->right !=NULL) {
*root = (*root)->right;
}else{
(*root)->right = node;
break;
}
}
}
}
/*
前序:节点,往左,再往右
中序:往左,节点,再往右
后序:往左,往右,再节点
所有函数的参数都是树根和作为打印函数的一个函数指针,它们都是递归的,只要传入的根节点非空就会调用自身
不同点只在于执行三步操作的顺序
*/
void preOrder(TreeNode *root,DISPLAY display){
if (root !=NULL) {
display(root->data);
preOrder(root->left,display);
preOrder(root->right, display);
}
}
void inOrder(TreeNode *root,DISPLAY display){
if (root !=NULL) {
inOrder(root->left,display);
display(root->data);
inOrder(root->right, display);
}
}
void postOrder(TreeNode *root,DISPLAY display){
if (root !=NULL) {
postOrder(root->left,display);
postOrder(root->right, display);
display(root->data);
}
}
int main(int argc,constchar * argv[]) {
Employee *samuel = (Employee *)malloc(sizeof(Employee));
strcpy(samuel->name,"samuel");
samuel->age = 32;
Employee *sally = (Employee *)malloc(sizeof(Employee));
strcpy(sally->name,"sally");
sally->age = 28;
Employee *susan = (Employee *)malloc(sizeof(Employee));
strcpy(susan->name,"susan");
susan->age = 56;
//Binary tree
TreeNode *tree = NULL;
insertNode(&tree, (COMPARE )compareEmployee, samuel);
insertNode(&tree, (COMPARE )compareEmployee, sally);
insertNode(&tree, (COMPARE )compareEmployee, susan);
preOrder(tree,(DISPLAY)displayEmployee);
inOrder(tree,(DISPLAY)displayEmployee);
postOrder(tree,(DISPLAY)displayEmployee);
return 0;
}
这棵树的逻辑结构:
输出:
samuel 32
sally 28
susan 56
sally 28
samuel 32
susan 56
sally 28
susan 56
samuel 32
Program ended with exit code: 0