本次代码实现的约定仅仅用于学习和交流
编程语言采用 C/C++
树的结构采用链式存储
结构操作:初始化结点、初始化树、销毁树、插入元素(采用二叉排序树的性质,左 < 中 < 右)、遍历(前、中、后,使用递归)、输出(采用广义表的形式)
#include#include #include // 结构定义 // 节点定义 typedef struct Node { int data; struct Node *lchild, *rchild; } Node; // 树 typedef struct Tree { Node *root; int length; } Tree; // 结构操作 // 初始化节点 Node *getNewNode(int val) { Node *p = (Node *)malloc(sizeof(Node)); p->data = val; p->lchild = p->rchild = NULL; return p; } // 二叉树初始化 Tree *getNewTree() { Tree *t = (Tree *)malloc(sizeof(Tree)); t->root = NULL; t->length = 0; return t; } // 插入 采用二叉排序树的形值, 左 < 中 < 右 // 递归调用,插入节点 Node *insert_node(Node *root, int val, int *flag) { if (root == NULL) { *flag = 1; // 传出参数 return getNewNode(val); } if (root->data == val) return root; if (root->data > val) root->lchild = insert_node(root->lchild, val, flag); else root->rchild = insert_node(root->rchild, val, flag); return root; } // 插入 void insert(Tree *t, int val) { if (t == NULL) return ; int flag = 0; t->root = insert_node(t->root, val, &flag); t->length += flag; return ; } // 三种遍历,前序、中序、后序 // 前序 void pre_order_node(Node *root) { if (root == NULL) return ; printf("%d ", root->data); pre_order_node(root->lchild); pre_order_node(root->rchild); return ; } void pre_order(Tree *t) { if (t == NULL) return ; printf("pre_order : "); pre_order_node(t->root); printf("n"); return ; } // 中序 void in_order_node(Node *root) { if (root == NULL) return ; in_order_node(root->lchild); printf("%d ", root->data); in_order_node(root->rchild); return ; } void in_order(Tree *t) { if (t == NULL) return ; printf("in_order : "); in_order_node(t->root); printf("n"); return ; } // 后序 void post_order_node(Node *root) { if (root == NULL) return ; post_order_node(root->lchild); post_order_node(root->rchild); printf("%d ", root->data); return ; } void post_order(Tree *t) { if (t == NULL) return ; printf("post_order : "); post_order_node(t->root); printf("n"); return ; } // 递归销毁节点 void clear_node(Node *node) { if (node == NULL) return ; clear_node(node->lchild); clear_node(node->rchild); free(node); return ; } // 销毁树 void clear(Tree *t) { if (t == NULL) return ; clear_node(t->root); free(t); return ; } // 输出二叉树,采用广义表的形式 void output_node(Node *root) { if (root == NULL) return ; printf("%d", root->data); if (root->lchild == NULL && root->rchild == NULL) return ; printf("("); output_node(root->lchild); printf(","); output_node(root->rchild); printf(")"); } void output(Tree *t) { if (t == NULL) return ; printf("tree(%d) : ", t->length); output_node(t->root); printf("n"); return ; } int main() { srand(time(0)); // 初始化随机种子 Tree *tree = getNewTree(); // 构造一棵树 #define MAX_OP 10 for (int i = 0; i < MAX_OP; i++) { int val = rand() % 100; // 获取随机值 insert(tree, val); output(tree); } #undef MAX_OP printf("n"); pre_order(tree); // 前序遍历 in_order(tree); // 中序遍历 post_order(tree); // 后序遍历 clear(tree); // 销毁树 return 0; }
感谢来访,有任何问题可以随时留言



