二叉树:二叉树是每个节点最多只有两个子节点的树,且子节点有左右之分。
满二叉树:一棵深度为k,且有2^k-1个节点的二叉树称为满二叉树。
完全二叉树:二叉树中,每个节点的序号都与相同的深度满二叉树序号完全一致,称为完全二叉树。
二叉树的遍历:二叉树的遍历通常有三种主要的方法,前序遍历、中序遍历和后序遍历,三种方法都是递归实现的。
1. 前序遍历
访问根节点
遍历左子树
遍历右子树
2. 中序遍历
遍历左子树
访问根节点
遍历右子树
3. 后序遍历
遍历左子树
遍历右子树
访问根节点
二叉树例子如下:
完整代码如下:
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *left;
struct node *right;
};
int tree_nodes[] = { 'A', 'B', 'D', '#', '#', '#', 'C', 'E',
'#', 'G', '#', '#', 'F', 'H', '#', '#', 'J', '#', '#'};
int node_index = 0;
void tree_destroy(struct node *leaf)
{
if (leaf != NULL) {
tree_destroy(leaf->left);
tree_destroy(leaf->right);
free(leaf);
}
}
void tree_create(struct node **leaf)
{
if (tree_nodes[node_index] == '#') {
*leaf = NULL;
node_index++;
} else {
*leaf = (struct node *)malloc(sizeof(struct node));
(*leaf)->data = tree_nodes[node_index++];
tree_create(&(*leaf)->left);
tree_create(&(*leaf)->right);
}
}
void preorder(struct node *root)
{
if (root != NULL) {
printf("%5c", root->data);
preorder(root->left);
preorder(root->right);
}
}
void inorder(struct node *root)
{
if (root != NULL) {
inorder(root->left);
printf("%5c", root->data);
inorder(root->right);
}
}
void postorder(struct node *root)
{
if (root != NULL) {
postorder(root->left);
postorder(root->right);
printf("%5c", root->data);
}
}
int main(void)
{
struct node *root;
tree_create(&root);
preorder(root);
printf("\n");
inorder(root);
printf("\n");
postorder(root);
printf("\n");
tree_destroy(root);
return 0;
}
二叉树的创建使用了前序遍历方式创建的,其中使用了'#'字符,如果遇见该符号,表示子节点为空。
前序遍历、中序遍历和后序遍历结果为:
A B D C E G F H J
D B A E G C H F J
D B G E H J F C A