二叉树
二叉树的简单操作函数
主要包括二叉树初始化 二叉排序树插入 前中后序遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| #include <stdio.h> #include <malloc.h>
typedef struct BTNode { int data; struct BTNode* left; struct BTNode* right; }BTNode;
BTNode* init() { BTNode* root = (BTNode*)malloc(sizeof(BTNode)); root->data = 5; root->left = NULL; root->right = NULL; return root; }
void insert(BTNode* root, int value) { if (value < root->data) { if (root->left == NULL) { BTNode* node; node = (BTNode*)malloc(sizeof(BTNode)); node->data = value; node->left = NULL; node->right = NULL; root->left = node; return; } insert(root->left, value); } else { if (root->right == NULL) {
BTNode* node; node = (BTNode*)malloc(sizeof(BTNode)); node->data = value; node->left = NULL; node->right = NULL; root->right = node; return;
} insert(root->right, value); } };
void midPrint(BTNode* root) { if (root != NULL) { midPrint(root->left); printf("%d", root->data); midPrint(root->right); } }
void prePrint(BTNode* root) { if (root != NULL) { printf("%d", root->data); prePrint(root->left); prePrint(root->right); } }
void postPrint(BTNode* root) { if (root != NULL) { postPrint(root->left); postPrint(root->right); printf("%d", root->data); } }
int main() { int a = 1; BTNode* root = init(); printf("%d\n",root->data); for (int i = 1; i <= 8; i++) { insert(root, i); } printf("中序遍历\n"); midPrint(root); printf("\n先序遍历\n"); prePrint(root); printf("\n后序遍历\n"); prePrint(root); return 0; }
|
运行结果
补充
以上代码能解决增改查,后续补上关于层次遍历和删除函数