#include <stdio.h>
#include <stdlib.h>
typedef struct btree bt;
struct btree {
int _val;
int _count;
bt *_lc;
bt *_rc;
};
* 挂载节点
* @param head 二叉树的根节点的指针
* @param val 待插叙节点的值
*/
void insert(bt const * const head, int const val) {
bt *node = malloc(sizeof(bt));
node->_val = val;
node->_count = 1;
node->_lc = NULL;
node->_rc = NULL;
bt *tmp = head;
while (1) {
if (tmp->_val == val) {
tmp->_count++;
return;
} else if (tmp->_val > val) {
if (tmp->_lc == NULL)
break;
else
tmp = tmp->_lc;
} else {
if (tmp->_rc == NULL)
break;
else
tmp = tmp->_rc;
}
}
if (tmp->_val > val)
tmp->_lc = node;
else
tmp->_rc = node;
}
* 构建二叉树
* @param arr 构建二叉树的输入-数组
* @param len 数组的长度
* @return 二叉树根节点的指针
*/
bt *buildTree(int const * const arr, size_t const len) {
bt *head = malloc(sizeof(bt));
head->_val = *(arr + len - 1);
head->_count = 1;
head->_lc = NULL;
head->_rc = NULL;
int i;
for (i = 1; i < len; ++i) {
insert(head, *(arr + i));
}
return head;
}
* 中序遍历(采用的递归算法)
* @param node 当前的"根"节点指针
*/
void travelMidSeq(bt const * const node) {
if (node->_lc != NULL)
travelMidSeq(node->_lc);
int i;
int len = node->_count;
for (i = 0; i < len; ++i)
printf("%d ", node->_val);
if (node->_rc != NULL)
travelMidSeq(node->_rc);
}
* 释放资源(递归算法)---实质就是后续遍历的算法
* @param node 当前需要处理的节点指针
* @param arr 要排序的数组的指针
*/
void releaseTreeAndCheck(bt *node) {
if (node->_lc != NULL)
releaseTreeAndCheck(node->_lc);
if (node->_rc != NULL)
releaseTreeAndCheck(node->_rc);
printf("%d ", node->_val);
free(node);
}
* 打印数组
* @param arr 数组的指针
* @param len 数组的长度
*/
void print(int const * const arr, size_t const len) {
int i;
printf("the front travel sequence of the tree:\n");
for (i = 0; i < len; ++i)
printf("%d ", *(arr + i));
}
int main(void) {
int arr[] = {8, 4, 2, 1, 3, 6, 5, 7, 12, 10, 9, 11, 14, 13, 15};
size_t len = sizeof(arr) / sizeof(int);
print(arr, len);
bt *tree = buildTree(arr, len);
printf("\nmiddle sequence travel result :\n");
travelMidSeq(tree);
printf("\nback sequence travel result :\n");
releaseTreeAndCheck(tree);
return 0;
}