二叉树节点
// 树节点
struct binary_tree
{
int data; // 数据
struct binary_tree *left; // 左叶子节点
struct binary_tree *right; // 右叶子节点
};
typedef struct binary_tree node;
插入节点
void insert(node ** tree, int val)
{
node *temp = NULL;
// 判断树节点是否为null,为null时生成节点插入到树中
if (NULL == (*tree))
{
temp = (node*)malloc(sizeof(node));
temp->left = NULL;
temp->right = NULL;
temp->data = val;
(*tree) = temp;
return;
}
// 已经存在的树节点,需要往左右子节点插入
if (val < (*tree)->data)
{
// 小于当前节点插入左边
insert(&(*tree)->left, val);
}else if (val > (*tree)->data)
{
// 大于当前节点插入到右边
insert(&(*tree)->right, val);
}
}
删除节点
void deltree(node *tree)
{
if (NULL != tree)
{
if (NULL != tree->left)
{
deltree(tree->left);
}
if (NULL != tree->right)
{
deltree(tree->right);
}
free(tree);
}
}
二叉树遍历
前序遍历
// 前序遍历,先输出data,再输出左右节点
void print_preorder(node *tree)
{
if (NULL != tree)
{
printf("%d \n", tree->data);
print_preorder(tree->left);
print_preorder(tree->right);
}
}
中序遍历
// 中序遍历,先输出左节点,再输出data,最后输出右节点
void print_inorder(node *tree)
{
if (NULL != tree)
{
print_inorder(tree->left);
printf("%d \n", tree->data);
print_inorder(tree->right);
}
}
后序遍历
// 后序遍历,先输出左右节点,在输出data
void print_postorder(node *tree)
{
if (NULL != tree)
{
print_postorder(tree->left);
print_postorder(tree->right);
printf("%d \n", tree->data);
}
}
代码
#include <stdio.h>
#include <stdlib.h>
struct binary_tree
{
int data;
struct binary_tree *left;
struct binary_tree *right;
};
typedef struct binary_tree node;
void insert(node ** tree, int val)
{
node *temp = NULL;
// 判断树节点是否为null,为null时生成节点插入到树中
if (NULL == (*tree))
{
temp = (node*)malloc(sizeof(node));
temp->left = NULL;
temp->right = NULL;
temp->data = val;
(*tree) = temp;
return;
}
// 已经存在的树节点,需要往左右子节点插入
if (val < (*tree)->data)
{
// 小于当前节点插入左边
insert(&(*tree)->left, val);
}else if (val > (*tree)->data)
{
// 大于当前节点插入到右边
insert(&(*tree)->right, val);
}
}
void deltree(node *tree)
{
if (NULL != tree)
{
if (NULL != tree->left)
{
deltree(tree->left);
}
if (NULL != tree->right)
{
deltree(tree->right);
}
free(tree);
}
}
// 前序遍历,先输出data,再输出左右节点
void print_preorder(node *tree)
{
if (NULL != tree)
{
printf("%d \n", tree->data);
print_preorder(tree->left);
print_preorder(tree->right);
}
}
// 中序遍历,先输出左节点,再输出data,最后输出右节点
void print_inorder(node *tree)
{
if (NULL != tree)
{
print_inorder(tree->left);
printf("%d \n", tree->data);
print_inorder(tree->right);
}
}
// 后序遍历,先输出左右节点,在输出data
void print_postorder(node *tree)
{
if (NULL != tree)
{
print_postorder(tree->left);
print_postorder(tree->right);
printf("%d \n", tree->data);
}
}
int main(void)
{
node *root = NULL;
insert(&root, 9);
insert(&root, 4);
insert(&root, 15);
insert(&root, 2);
insert(&root, 6);
insert(&root, 12);
insert(&root, 17);
print_preorder(root);
getchar();
deltree(root);
return 0;
}
参考:https://www.cnblogs.com/landpack/p/4783120.html