1. 二叉树的存储结构
二叉树的存储结构主要有两种。相对一般的树而言,二叉树比较特殊,存储也相对更简单明确。二叉树也是最常用的树。
如果二叉树接近满,那么可以使用顺序存储,因为二叉树的特殊性质,我们根据位置可以直接推算出它在树中的位置。如果是一般的二叉树的话,最常用的的还是二叉链表,即每个节点有两个指针,分别指向左子树和右子树。
2. 二叉树的遍历
二叉树的遍历主要是前序、中序和后续三种方式。其中前序遍历实际上是深度优先遍历。不多说,上代码。都是递归方式实现。
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node* left;
struct node* right;
} node;
void createBinaryTree(node* root)
{
int input;
scanf("%d", &input);
if (input == -1)
{
root = NULL;
}
else
{
root = (node*)malloc(sizeof(node));
*root->data = input;
createBinaryTree(*root->left);
createBinaryTree(*root->right);
}
}
void firstRootVisit(node* root)
{
if (root == NULL)
{
return;
}
else
{
printf("%d ", *root->data);
firstRootVisit(*root->left);
firstRootVisit(*root->right);
}
}
void lastRootVisit(node* root)
{
if (root == NULL)
{
return;
}
else
{
lastRootVisit(*root->left);
lastRootVisit(*root->right);
printf("%d ", *root->data);
}
}
void middleRootVisit(node* root)
{
if (root == NULL)
{
return;
}
else
{
middleRootVisit(*root->left);
printf("%d ", *root->data);
middleRootVisit(*root->right);
}
}
int main()
{
node* root;
createBinaryTree(root);
firstRootVisit(root);
lastRootVisit(root);
middleRootVisit(root);
return 0;
}